简体   繁体   English

Tkinter中的销毁方法

[英]destroy method in tkinter

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)

This is part of the code for a game i am trying to write. 这是我尝试编写的游戏代码的一部分。 I am wondering why is it that when i click on the qbutton it does not destroy the window. 我想知道为什么当我单击qbutton时它不会破坏窗口。 I need it so that when i push on the button i also change the value of dogame so i cannot simply set command=root.destroy 我需要它,所以当我按下按钮时,我也会更改dogame的值,所以我不能简单地设置command = root.destroy

Command requires a function. 命令需要功能。 You have provided the return value of a function. 您已提供函数的返回值

You meant 你的意思是

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

By removing the parentheses from quitt , we are no longer evaluating it. 通过从quitt除去括号,我们不再对其进行评估。 Since functions are first-class objects in python, we can pass them around like anything else. 由于函数是python中的一流对象,因此我们可以像其他任何东西一样传递它们。 Once you call the function, you're passing whatever it returns. 调用该函数后,您将传递它返回的任何内容。 In this case, the fact that it returns None, implicitely, masked the mistake 在这种情况下,该函数隐式返回None的事实掩盖了错误

Note that you considered using root.destroy ; 请注意,您考虑使用root.destroy this is notable different from using root.destroy() with the call-syntax 这与在调用语法中使用root.destroy()明显不同

When you assign command = quitt() you are calling that function at the time the button is being built, and then adding what that function returns ( None ) to the command call. 当您分配command = quitt()时,您将在构建按钮时调用该函数,然后将该函数返回的内容( None )添加到命令调用中。

Instead, add the callable to the command: 而是将callable添加到命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM