[英]Python tkinter When Toplevel object is destroyed, With toplevel binding for <Destroy> the bound command executes multiple times
[英]Why is Tkinter Toplevel object being destroyed?
在下面的代碼中, tk
不是函數launch()
創建的Toplevel
對象的父級。 但是,當我使用tk.destroy()
銷毀tk
, tk.destroy()
窗口消失了。
頂級寡婦被摧毀了嗎? 如果是這樣,那么如何調用Toplevel.destroy()
?
from tkinter import *
def launch():
Toplevel()
tk = Tk()
frame = Frame(tk, relief="ridge", borderwidth=2)
frame.pack(fill="both", expand=1)
label = Label(frame, text="Hello, World")
label.pack(fill=X, expand=1)
button1 = Button(frame, text="Exit", command=tk.destroy)
button2 = Button(frame, text="Launch", command=launch)
button1.pack(side="bottom")
button2.pack(side="bottom")
tk.mainloop()
使您的應用程序運行的是Tk
實例的mainloop,它是所有小部件的父級。 銷毀它時,所有小部件也會被銷毀。
請記住,對於每個Tk實例,都有一個關聯的Tcl解釋器,我將根據Tk的docs字符串以及tkinter模塊的關聯類和方法,嘗試給出關閉窗口時會發生的更詳細的答案。 。
Tk源自2類: Misc和Wm 。 在Misc類中,您可以找到quit方法的接口和文檔:
def quit(self):
"""Quit the Tcl interpreter. All widgets will be destroyed."""
self.tk.quit()
您可以在Tk類的destroy
方法下找到以下內容:
def destroy(self):
"""Destroy this and all descendants widgets. This will
end the application of this Tcl interpreter."""
在某些時候, Tk類中的destroy方法還調用Misc類的destroy方法,在那里您還可以找到另一個文檔:
def destroy(self):
"""Internal function.
Delete all Tcl commands created for
this widget in the Tcl interpreter."""
這並不表示Tcl解釋器也已停止(就像上述quit方法一樣)。
構造Tk實例時,將調用一個名為_loadtk
的方法。 在此方法中,設置了關閉Tk窗口時的protocol
:
self.protocol("WM_DELETE_WINDOW", self.destroy)
如您所見, destroy
(而不是quit )與窗口的關閉事件相關。
這一切都意味着,當您關閉窗口時,Tk實例及其所有子代將被銷毀,但Tcl解釋器不會停止。
Tkinter.Tk
是所有Tkinter.Tk
窗口的大Tkinter.Tk
。 它運行邏輯並與OS通信。 一切順利-他們全都去了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.