我在python中有一个Tkinter应用程序,我正试图在其中使用一个自定义的对话框。因此,我有一个主App
类和一个扩展Toplevel
的Dialog
类。在App
类的主体中,Dialog
需要弹出并允许用户输入信息,然后可以将信息传递给主App
。
我知道我需要使用wait_window()
方法,以便主应用程序在继续代码之前等待对话框被销毁。但由于某种原因,即使在我退出对话框后,程序也无法继续。
我有看起来像的代码
class App:
def __init__(self):
self.root = Tk()
#more init code...
#more unrelated methods...
def analyze(self):
dialog = Dialog()
self.root.wait_window(dialog)
print("Continuing...")
#use the data collected in 'dialog'
class Dialog(Toplevel):
def __init__(self):
Toplevel.__init__(self)
#set up the components of the dialog
#all input data gets saved as instance variables so I can access it
self.mainloop()
def destroy(self):
print("Destroying")
Toplevel.destroy(self)
当我运行应用程序时,对话框会按预期显示,并按预期工作。然而,当我按下角落里的红色X时,程序不会继续。对话框关闭并打印"Destroying",因此我知道正在调用destroy
方法,但"Continuing"未打印,也未使用任何数据。
我试着在对话框中添加一个按钮,该按钮调用self.destroy
作为显式销毁它的命令。我也试着不重写Dialog
中的destroy
方法来查看是否是这导致了它,但这些都不起作用。
我还试着用dialog.wait_window()
代替self.root.wait_window(dialog)
,看看这是否有帮助,但没有。
非常感谢您的帮助。如果需要更多的代码,我可以提供。提前谢谢。
不要再次调用mainloop()
。在程序的生命周期中,mainloop()
应该总是被调用一次。