2011-10-07 68 views

回答

3

MVC与非Web应用程序一样适用。唯一改变的是View(GUI控件而不是Web控件)以及Controller可以/必须处理的输入类型。

1

实用程序类型程序最直接的方法就像下面的伪代码 - 是Python与PyGTK的提示。想象一下以某种方式操作文件的实用程序。

class File(object): 
    """This class handles various filesystem-related tasks.""" 

    def __init__(self, path): 
     pass 

    def open(self): 
     pass 

    def rename(self, new_name): 
     pass 

    def move(self, to): 
     pass 


class Window(gtk.Window): 
    """This class is the actual GUI window with widgets.""" 

    def __init__(self): 
     self.entry_rename = gtk.Entry() 
     self.entry_move = gtk.Entry() 
     self.btn_quit = gtk.Button('Quit') 


class App(object): 
    """This is your main app that displays the GUI and responds to signals.""" 

    def __init__(self): 
     self.window = Window() 

     # signal handlers 
     self.window.connect('destroy', self.on_quit) 
     self.window.entry_rename.connect('changed', self.on_rename_changed) 
     self.window.entry_move.connect('changed', self.on_move_changed) 
     self.window.btn_quit.connect('clicked', self.on_quit) 
     # and so on... 

    def on_quit(self): 
     """Quit the app.""" 
     pass 

    def on_rename_changed(self): 
     """User typed something into an entry box, do something with text.""" 
     f = File('somefile.txt') 
     f.rename(self.entry_rename.get_text()) 

    def on_move_changed(self): 
     """User typed something into another entry box, do something with text.""" 
     f = File('somefile.txt') 
     f.move(self.entry_move.get_text()) 

你可以认为这是一个非正式的MVC:File是你的模型,Window是视图和App是控制器。

当然,还有其他更正式的方法。大多数Python GUI工具包的Wiki都有关于可能的arhitectures的文章。例如,参见wxPython wiki article on MVC。还有一个PyGTK的MVC框架,名为pygtkmvc

我有一个意见,除非你确定你需要这样一个正式的方法,你最好使用类似以上的代码。 Web框架受益于更正式的方法,因为还有更多要连接的部分:HTTP请求,HTML,JavaScript,SQL,业务逻辑,表示逻辑,路由等,即使是最简单的应用程序也是如此。使用典型的Python GUI应用程序,您只需要使用Python处理业务逻辑和事件处理。