【问题标题】:destroy method in tkintertkinter 中的销毁方法
【发布时间】:2015-12-08 15:52:01
【问题描述】:
class Clicked(): 
    dogame=True

    def __init__(self):
        None


    def change(self): 
       self.dogame=False

currentgame=Clicked()
root = Tk()

def quitt(): 
    root.destroy()
    currentgame.change()

qbutton = Button(base, text = "Quit", command = quitt(), foreground = "Red", **kwargs)
qbutton.pack(side = BOTTOM)

这是我正在尝试编写的游戏代码的一部分。我想知道为什么当我单击 qbutton 时它不会破坏窗口。我需要它,这样当我按下按钮时,我也会更改 dogame 的值,所以我不能简单地设置 command=root.destroy

【问题讨论】:

    标签: python tkinter destroy


    【解决方案1】:

    命令需要一个函数。您提供了一个函数的返回值

    你是说

    qbutton = Button(base, text = "Quit", command = quitt, foreground = "Red", **kwargs)
    

    通过删除quitt 中的括号,我们不再对其进行评估。由于函数是 python 中的一等对象,我们可以像其他任何东西一样传递它们。调用该函数后,您将传递它返回的任何内容。在这种情况下,它隐含地返回 None 的事实掩盖了错误

    请注意,您考虑过使用root.destroy;这与使用带有调用语法的root.destroy() 有显着不同

    【讨论】:

      【解决方案2】:

      当您分配 command = quitt() 时,您正在构建按钮时调用该函数,然后将该函数返回的内容 (None) 添加到命令调用中。

      相反,将可调用对象添加到命令中:

      qbutton = Button(base, text = "Quit", command = quitt, foreground = "Red", **kwargs)
      

      【讨论】:

      • 我想我比你快 5 毫秒 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2015-03-10
      • 1970-01-01
      • 2014-09-28
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多