Notice how this GUI’s windows use a window’s destroy method to close just one
window, instead of sys.exit to shut down the entire program; to see how this method
really does its work, let’s move on to window protocols.
Top-Level Window Protocols
Both Tk and Toplevel widgets export extra methods and features tailored for their top-
level role, as illustrated in Example 8-5.
Example 8-5. PP4E\Gui\Tour\toplevel2.py
"""
pop up three new windows, with style
destroy() kills one window, quit() kills all windows and app (ends mainloop);
top-level windows have title, icon, iconify/deiconify and protocol for wm events;
there always is an application root window, whether by default or created as an
explicit Tk() object; all top-level windows are containers, but they are never
packed/gridded; Toplevel is like Frame, but a new window, and can have a menu;
"""
from tkinter import *
root = Tk() # explicit root
trees = [('The Larch!', 'light blue'),
('The Pine!', 'light green'),
('The Giant Redwood!', 'red')]
for (tree, color) in trees:
win = Toplevel(root) # new window
win.title('Sing...') # set border
win.protocol('WM_DELETE_WINDOW', lambda:None) # ignore close
win.iconbitmap('py-blue-trans-out.ico') # not red Tk
msg = Button(win, text=tree, command=win.destroy) # kills one win
msg.pack(expand=YES, fill=BOTH)
msg.config(padx=10, pady=10, bd=10, relief=RAISED)
msg.config(bg='black', fg=color, font=('times', 30, 'bold italic'))
root.title('Lumberjack demo')
Label(root, text='Main window', width=30).pack()
Button(root, text='Quit All', command=root.quit).pack() # kills all app
root.mainloop()
This program adds widgets to the Tk root window, immediately pops up three
Toplevel windows with attached buttons, and uses special top-level protocols. When
run, it generates the scene captured in living black-and-white in Figure 8-4 (the buttons’
text shows up blue, green, and red on a color display).
422 | Chapter 8: A tkinter Tour, Part 1