2015-02-06 143 views
1

在下面的代碼中,tk不是由函數launch()創建的Toplevel對象的父代。但是,當我使用tk.destroy()銷燬tk時,Toplevel窗口消失。爲什麼Tkinter Toplevel物體被破壞?

Toplevel寡婦被摧毀了嗎?如果是這樣,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() 

回答

5

讓您的應用程序運行的是Tk實例的主循環,它是所有小部件的父項。當你銷燬它時,所有的部件也被銷燬。


記住,對於每個Tk的情況下,有一個相關的的Tcl解釋,我會盡量給上,當你關閉一個窗口會發生什麼情況的基礎上,傳統知識文檔串的更詳細的解答以及模塊的相關類和方法。

Tk派生自2個類別:雜項Wm。在雜項類中,你可以找到的接口,併爲文檔退出方法:

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類調​​用也在某個點,破壞方法雜項 cl屁股,在那裏你還可以找到另一個文檔:

def destroy(self): 
    """Internal function. 
    Delete all Tcl commands created for 
    this widget in the Tcl interpreter.""" 

哪個不說,還Tcl解釋停止(像退出上述方法)。

構建Tk實例時,調用名爲_loadtk的方法。在這種方法中,它被設置在在關閉窗口Tk的:

self.protocol("WM_DELETE_WINDOW", self.destroy) 

,你可以看到,destroy(而不是退出)與窗口的關閉事件相關聯。


這一切都意味着,當你關閉該窗口,Tk的實例及其所有子被破壞,但Tcl解釋不停止。

3

Tkinter.Tk是所有的Tkinter窗口的大波帕鼻祖。它運行邏輯並與操作系統進行通信。當它走了 - 他們都走了。