Tk 和 Toplevel 之间的区别

Tk 是应用程序的绝对根,它是第一个需要实例化的窗口小部件,GUI 在销毁时会关闭。

Toplevel 是应用程序中的一个窗口,关闭窗口将销毁放置在该窗口{1}上的所有子窗口小部件,但不会关闭该程序。

try:
    import tkinter as tk #python3
except ImportError:
    import Tkinter as tk #python2

#root application, can only have one of these.
root = tk.Tk() 

#put a label in the root to identify the window.
label1 = tk.Label(root, text="""this is root
closing this window will shut down app""")
label1.pack()

#you can make as many Toplevels as you like
extra_window = tk.Toplevel(root)
label2 = tk.Label(extra_window, text="""this is extra_window
closing this will not affect root""")
label2.pack()

root.mainloop()

如果你的 python 程序只代表一个应用程序(它几乎总是会这样),那么你应该只有一个 Tk 实例,但你可以创建任意数量的 Toplevel 窗口。

try:
    import tkinter as tk #python3
except ImportError:
    import Tkinter as tk #python2

def generate_new_window():
    window = tk.Toplevel()
    label = tk.Label(window, text="a generic Toplevel window")
    label.pack()

root = tk.Tk()

spawn_window_button = tk.Button(root,
                                text="make a new window!",
                                command=generate_new_window)
spawn_window_button.pack()

root.mainloop()

{1}:如果 Toplevel(A = Toplevel(root))是另一个 Toplevel(B = Toplevel(A))的父级,则关闭窗口 A 也将关闭窗口 B.