2016-12-29 2547 views
1

我想教自己的Python这样的东西可能是一个愚蠢的问题,但是这已经快把我逼疯了几天道歉。我看了看这里的同一主题的其他问题,但似乎仍然没有能够得到这个工作。关闭一个Toplevel的窗口的Tkinter

我创建了一个顶层窗口,要求提示用户,并希望该窗口当用户按自己选择的按钮关闭。这就是问题的所在,我不能让它关闭为爱或金钱。我的代码包含在下面。

感谢这么多的帮助。

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 

谢谢

回答

2

调用该方法确实destroy,在pop对象。

然而,yesButton方法里面,pop指东西是未知的。

当初始化你的对象,在__init__方法,你应该把pop项目为self属性:

self.pop = Toplevel() 

然后,你yesButton方法里面,调用self.pop对象的destroy方法:

self.pop.destroy() 

关于0123之间的差异和pop.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方法。

+0

非常感谢您提供这样一个清晰简洁的答案右腿,这已经解决了我的问题,并在调用方法时帮助我了解将来的知识。很好的答案,也很快,再次感谢 – Shallon

相关问题