2011-10-07 44 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處理業務邏輯和事件處理。