【问题标题】:AttributeError when change the command method for a Button in Tkinter在 Tkinter 中更改按钮的命令方法时出现 AttributeError
【发布时间】:2012-10-06 06:35:01
【问题描述】:


我正在使用 Tkinter 的 Python GUI 程序。在controller.py的构造器中,我想给BackButton命令打开closeFrame函数(command = self.closeFrame)。
view.py

class View(TK):
  def SCPIMenu(self):
    self.BackButton = Button(self.SCPIFrame, text = "Back", command = None)
    self.BackButton.place(x = 30, y = 330, anchor = CENTER)

controller.py

class Controller(object):
  def __init__(self):
    self.view = View()
    self.view.mainMenu()
    self.view.mainloop()

 def closeFrame(self):
   self.SCPIFrame.destroy()

c = Controller()


我想像 self.view.BackButton.configure(command = self.closeFrame),但随后出现错误
AttributeError: BackButton

有什么想法吗? 感谢您的宝贵时间。

【问题讨论】:

    标签: button methods attributes command tkinter


    【解决方案1】:

    您的错误消息显示view 没有BackButton 属性。 通常,您在创建 self.view.BackButton 之前对其进行操作。

    提示:您的按钮似乎是在 SCPIMenu 中创建的,这不是从 Controller 构造函数中明确调用的。您可能希望将回调存储在视图中的某个位置,并在创建按钮时将其用作命令。

    【讨论】:

    • 感谢您的回答。问题是,我想将逻辑保留在控制器类中。视图只包含GUI,没有任何功能。
    • 不要明白你的意思,当你写self.view.BackButton.configure(command = self.closeFrame)时,你在一个视图元素中存储了一个对控制器函数的引用(回调的用途)。我看不到 Controller 执行 self.view.backCallback = self.closeFrame 和更高版本(在按钮实例化时)Button(... command = self.view.backCallback) 的区别
    • 我现在有点困惑。在视图类中,只有所有的 GUI 元素,没有命令和功能。在控制器类中,有按钮的所有功能,在它的构造器中,我想为按钮和通用 GUI 设置命令。
    猜你喜欢
    • 2010-09-09
    • 2021-09-17
    • 2019-05-06
    • 1970-01-01
    • 2019-10-06
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多