Example 8-3. PP4E\Gui\Tour\toplevel0.py
import sys
from tkinter import Toplevel, Button, Label
win1 = Toplevel() # two independent windows
win2 = Toplevel() # but part of same process
Button(win1, text='Spam', command=sys.exit).pack()
Button(win2, text='SPAM', command=sys.exit).pack()
Label(text='Popups').pack() # on default Tk() root window
win1.mainloop()
The toplevel0 script gets a root window by default (that’s what the Label is attached to,
since it doesn’t specify a real parent), but it also creates two standalone Toplevel win-
dows that appear and function independently of the root window, as seen in
Figure 8-3.
Figure 8-3. Two Toplevel windows and a root window
The two Toplevel windows on the right are full-fledged windows; they can be inde-
pendently iconified, maximized, and so on. Toplevels are typically used to implement
multiple-window displays and pop-up modal and nonmodal dialogs (more on dialogs
in the next section). They stay up until they are explicitly destroyed or until the appli-
cation that created them exits.
In fact, as coded here, pressing the X in the upper right corner of either of the
Toplevel windows kills that window only. On the other hand, the entire program and
all it remaining windows are closed if you press either of the created buttons or the
main window’s X (more on shutdown protocols in a moment).
It’s important to know that although Toplevels are independently active windows, they
are not separate processes; if your program exits, all of its windows are erased, including
all Toplevel windows it may have created. We’ll learn how to work around this rule
later by launching independent GUI programs.
420 | Chapter 8: A tkinter Tour, Part 1