为什么Tkinter Toplevel对象被摧毁?

akr*_*amo 1 python tkinter

在下面的代码中,tk不是Toplevel函数创建的对象的父级launch().然而,当我破坏tk使用时tk.destroy(),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()
Run Code Online (Sandbox Code Playgroud)

nbr*_*bro 5

使应用程序运行的是Tk实例的主循环,它是所有小部件的父级.当你销毁它时,所有小部件也会被销毁.


请记住,对于每个Tk实例,都有一个关联的Tcl解释器,我将尝试根据Tk的文档字符串以及tkinter模块的相关类和方法,给出关闭窗口时会发生什么的更详细的答案..

Tk来自2个类:MiscWm.在Misc类中,您可以找到quit方法的界面和文档:

def quit(self):
    """Quit the Tcl interpreter. All widgets will be destroyed."""
    self.tk.quit()
Run Code Online (Sandbox Code Playgroud)

您可以destroy在Tk类的方法下找到以下内容:

def destroy(self):
    """Destroy this and all descendants widgets. This will
    end the application of this Tcl interpreter."""
Run Code Online (Sandbox Code Playgroud)

Tk类中的destroy方法在某些时候也调用了Misc类的destroy方法,在那里你还可以找到另一个文档:

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

这并没有说Tcl解释器也被停止了(就像上面描述的quit方法一样).

构造Tk实例时,调用一个_loadtk被调用的方法.在此方法中,设置protocolTk窗口关闭的时间:

self.protocol("WM_DELETE_WINDOW", self.destroy)
Run Code Online (Sandbox Code Playgroud)

如您所见,destroy(而不是退出)与窗口的关闭事件相关联.


这意味着当您关闭窗口时,Tk实例及其所有子节点都将被销毁,但Tcl解释器不会停止.