关闭Toplevel Tkinter窗口

时间:2016-12-29 11:13:26

标签: python tkinter toplevel

我试图教自己Python为这可能是一个愚蠢的问题道歉但这已经让我疯了几天。我在这里看了同一主题的其他问题,但似乎还没有能够让它发挥作用。

我创建了一个顶级窗口,要求用户提示,并希望当用户按下他们选择的按钮时关闭窗口。这就是问题所在,我无法通过爱情或金钱来关闭它。我的代码包含在下面。

非常感谢您的帮助。

from Tkinter import *

root = Tk()

board = Frame(root)
board.pack()

square = "Chat"
cost = 2000

class buyPrompt:

         def __init__(self):
            pop = Toplevel()

            pop.title("Purchase Square")

            Msg = Message(pop, text = "Would you like to purchase %s for %d" %                         (square, cost))
            Msg.pack()


            self.yes = Button(pop, text = "Yes", command = self.yesButton)
            self.yes.pack(side = LEFT)
            self.no = Button(pop, text = "No", command = self.noButton)
            self.no.pack(side = RIGHT)

            pop.mainloop()
         def yesButton(self):
                        return True
                        pop.destroy
         def noButton(self):
                        return False

我尝试了很多不同的做法pop.destroy,但似乎都没有用,我尝试的事情都是;

pop.destroy()
pop.destroy
pop.exit()
pop.exit

谢谢

1 个答案:

答案 0 :(得分:3)

destroy对象上的调用方法确实是pop

但是,在yesButton方法中,pop指的是未知的内容。

初始化对象时,在__init__方法中,您应将pop项目作为self的属性:

self.pop = Toplevel()

然后,在yesButton方法内,调用destroy对象上的self.pop方法:

self.pop.destroy()

关于pop.destroypop.destroy()之间的差异:

在Python中,几乎所有东西都是一个对象。所以方法也是一个对象。

当您编写pop.destroy时,您将引用名为destroy且属于pop对象的方法对象。它与撰写1"hello"基本相同:它不是声明,或者如果您愿意,不是动作

当您编写pop.destroy()时,您告诉Python 调用 pop.destroy对象,即执行其__call__方法。

换句话说,编写pop.destroy将无效(除了在交互式解释器中运行时打印<bound method Toplevel.destroy of...>之类的内容),而pop.destroy()将有效地运行pop.destroy方法

相关问题