【问题标题】:how to separate view and controller in python tkinter?如何在 python tkinter 中分离视图和控制器?
【发布时间】:2013-07-11 15:48:55
【问题描述】:

我对 tkinter 有一个关于在两个模块中分离 UI 和 UI 功能的问题,这是我的代码:

1-view.py

from tkinter import *

class View():
    def __init__(self,parent):
        self.button=Button(parent,text='click me').pack()

2.controller.py

from tkinter import *
from view import *

class Controller:
    def __init__(self,parent):
        self.view1=View(parent)
        self.view1.button.config(command=self.callback)

    def callback(self):
        print('Hello World!')


root=Tk()
app=Controller(root)
root.mainloop()

在运行 controller.py 时出现以下错误:

AttributeError: 'NoneType' 对象没有属性 'config'

有什么建议吗?

我也尝试使用 lambda 在另一个模块中使用回调函数,但它不起作用。

提前致谢

【问题讨论】:

    标签: python model-view-controller python-3.x lambda tkinter


    【解决方案1】:

    lambda 方法问题与上面完全相同,现在通过在新行中使用包来解决。它看起来更漂亮,这是使用 lambda 的示例,它工作正常:

    1.view.py

    from tkinter import *
    from controller import *
    
    class View():
        def __init__(self,parent):
            button=Button(parent,text='click me')
            button.config(command=lambda : callback(button))
            button.pack()
    
    
    root=Tk()
    app=View(root)
    root.mainloop()
    

    2.controller.py

    def callback(button):
        button.config(text='you clicked me!')
        print('Hello World!')
    

    使用这种方法,我们可以将所有功能从 UI 中移出,并使其干净易读。

    【讨论】:

      【解决方案2】:

      在 view.py 你正在调用:

      self.button=Button(parent,text='click me').pack()

      pack 函数没有返回您要分配给 self.button 的 Button 对象,这会导致稍后的 AttributeError。你应该这样做:

      self.button = Button(parent, text='click me')
      self.button.pack()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-05
        • 2012-03-22
        • 2011-12-12
        • 2012-10-23
        • 1970-01-01
        • 2012-09-17
        • 2018-12-27
        相关资源
        最近更新 更多