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.