python - 使用 python 的桌面 GUI 中的 MVC 模式

标签 python model-view-controller user-interface view controller

我的问题如下。来自 Web 背景,我没有遇到这样做的问题,但在 Python 桌面应用程序中,我真的看不出什么是根据 MVC 模式组织代码的最佳方式。

我想根据用户输入创建一个窗口,当按下按钮时,它会显示数据库中可用的类似条目。 window 就是我的风景。

所以基本上这些是关系:

enter image description here

1) 通信 Controller --> View

Controller 有一个 View 实例,可以使用它公开的方法,例如 view.show_data()。我认为这是要走的路。

# Controller
my_view = View()
...
my_view.show_data(whatever_data)

2) 通信 View --> Controller

当用户插入一些文本时,必须触发 Controller 中的一个方法,以便它可以向模型请求数据库中的必要数据。问题是我不知道 View 告诉 Controller 它必须触发那个方法的最佳方式是什么。

我的第一个想法是将 Controller 的引用传递给 View ,并在 View 上绑定(bind)事件,如下所示:

# Controller
my_view = View(self)
my_model = Model()
...

def on_user_input(self):
     # process the input
     user_input = ...
     self.my_model.method_to_get_info(user_input)

和 View :

# View
def __init__(self, controller):
    self.controller_reference = controller
    self.launch_gui()
    self.config_binds()

def launch_gui(self):
    # ... configure all the GUI itself
    self.button = ...


def config_binds(self):
    self.button.Bind(wx.EVT_BUTTON, self.controller_reference.on_user_input())

但我认为这种“闭环”关系并不是一个非常干净的解决方案。 View 在 Controller 中被引用, Controller 在 View 中被引用。我认为它在 View 和 Controller 之间建立了紧密的关系。

有什么方法可以做到这一点?

最佳答案

该 View 应该触发事件。通常您不会将事件直接发送到 Controller ,而是 GUI 的框架通用事件处理程序。所讨论的事件通常是诸如“已按下某个键”和“有人移动了鼠标”之类的事件。

在您的情况下,一个更“高级”的 MVC 可以很好地让各部分相互了解。你告诉 View 它的 Controller 是什么对象是完全没问题的。重要的是所有部分都使用一个定义良好的接口(interface),因此这些部分是可以互换的。

如您所见,这与模型- View - Controller 的常见 Web 概念完全不同,模型- View - Controller 实际上根本不是模型- View - Controller ,而是用词不当,应称为模型- View -模板。

关于python - 使用 python 的桌面 GUI 中的 MVC 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14214664/

相关文章:

python - Django 外键访问是如何工作的

java - 如何在 Android 中使用 MVC 模式从 firebase 检索数据?

java - 与 MVC Servlet/JSP 应用程序相比,Java EE 应用程序如何扩展?

c - 如何为我的 Gtk+ 应用程序设置默认主题?

javascript - jQuery 加载窗口,同时等待长函数完成

java - XML 中的 UI 布局和元素

Python 多处理队列比 pool.map 慢

python - 使用可变 C 数组从 C 线程调用 Python 函数

python - 如何使用 Python MySQdb 检查记录是否存在

WCF 作为 BLL(中间层)和安全技术