大家好:
我最近在用 python 写一个程序框架,使用这个框架,python 程序员可以只需要
定义用户接口,而不用编写相关的实际代码就可以在运行时拥有希望的图形用户
界面,有点玄乎吗?说明白了其实也很简单。
大家都知道大名鼎鼎的 MVC 吧,一个需要和用户界面的程序都可以分为三个部
份:Model, View, Controller;Model 是程序的逻辑,这于具体的应用有
关;View 是程序的表示,也就是我们用眼睛看到的东西;Controller 这用于响
应用户的输入,如当点击一个按钮后运行一个函数后改变一个变量的值。
通常的程序结构如下:
[ Model ]
|
V
[ Controller ]
|
V
[ View ]
从中可以看出 Controller 是连接用户显示和程序逻辑的纽带,而我的这个框架
的中心也是 Controller。
基本的思想就是通过定义 Controller 类来定义用户接口。我将 Controller 分
为基本的三类:Action, Parameter, 和 Container。Action 对应函数等可执行
对象,Parameter 对应变量等数值对象,Container 则是一个容器,其中可以包
含任何其他的 Controller。一个应用程序 (Application) 本身也是一个
Controller,是容器的子类。这样一个应用程序的用户控制就使用这个
Controller 树描述出来了。然后定义一组 View 类来对这个 Controller 树进行
解析就可以为这个应用程序生成用户界面。例如写一组 GtkView 类来将控制器翻
译成对应的 gtk Widgets。这个 GtkView 类可以写的很通用,这样大多数的程序
都可以用这个 GtkView 来生成 Gtk 风格的用户界面。同时如果在写一个
NewtView 就可以为应用程序生成 Newt 风格的用户界面。还可以写 wxWindow 风
格的 View 等等。这样同一个程序,不需要些一行 Gtk 或 Newt 或 wxWindow 的
代码就可以同时拥有这些风格的界面。
基于上面的想法,我实现了一个用于测试的系统,其中几个基本的类的说明如下:
Argument 是 Parameter 的子类,用于控制一个变量。
Operation 是 Action 的子类,对应到一个函数或其他可调用的对象。
Group 是 Container 的子类,对应一组有关连的 Controller。
Form 是 Group 的子类,通常对应一个窗口。
Application 代表一个应用程序。
另外还有一些用于特殊界面要求的类,如:
Notebook 是 Group 的子类,运行是会使用 Notebook 来显示其中的内容。
Wizard 是 Group 的子类,运行是会使用向导方式。
以下是我测试用的一些例子:
一个复制文件的程序
copy.py 中包含 copy 函数的定义:
def copy(source, target, force=False, recursive=False):
......
copyui.py 中以定义 Controllers:
from copy import copy
from control import *
# 用于保存用户输入的变量
source = None
target = None
force = False
recursive = False
controllers = [
Argument("source", prompt="Source", help="source file or directory to copy from"),
Argument("target", prompt="Target", help="target file or directory to copy to"),
Argument("force", prompt="Force", help="force overwrite target files"),
Argument("recursive", prompt="Recursive", help="copy files in directories recursively"),
Operation(copy,
args="source, target, force=force, recursive=recursive",
prompt="Copy",
help="do the copy")
]
app = Application("Copy file", controllers)
app.run("gtk")
运行程序 copyui.py 就会显示一个 gtk 风格的界面。
将 app.run("gtk") 改为 app.run("newt") 就会显示 newt 风格的界面。
如果将创建 Application 对象的哪一行改为:
app = Application("Copy file", Wizard("Copy file", controllers))
就会使用 Druid 显示向导界面,除去首尾,分为五个步骤,每个步骤对应
controllers 中的一个 controller。如果将 controllers 改为:
controllers = [
Group("Source and target",[
Argument("source", prompt="Source", help="source file or directory to copy from"),
Argument("target", prompt="Target", help="target file or directory to copy to"),]),
Group("Options",[
Argument("force", prompt="Force", help="force overwrite target files"),
Argument("recursive", prompt="Recursive", help="copy files in directories recursively"),]),
Operation(copy,
args="source, target, force=force, recursive=recursive",
prompt="Copy",
help="do the copy")
]
再次运行就会只有三个步骤,前两个步骤的内容发生了变化。
是不是有点意思,这个框架目前还处在设计当中。如果大家感兴趣可以与我讨
论,晚些时候我会将测试的系统提供给有兴趣的人。
|
|