def dialog():
win = Toplevel() # make a new window
Label(win, text='Hard drive reformatted!').pack() # add a few widgets
Button(win, text='OK', command=win.destroy).pack() # set destroy callback
if makemodal:
win.focus_set() # take over input focus,
win.grab_set() # disable other windows while I'm open,
win.wait_window() # and wait here until win destroyed
print('dialog exit') # else returns right away
root = Tk()
Button(root, text='popup', command=dialog).pack()
root.mainloop()
This script is set up to create a pop-up dialog window in either modal or nonmodal
mode, depending on its makemodal global variable. If it is run with no command-line
arguments, it picks nonmodal style, captured in Figure 8-18.
Figure 8-18. Nonmodal custom dialogs at work
The window in the upper right is the root window here; pressing its “popup” button
creates a new pop-up dialog window. Because dialogs are nonmodal in this mode, the
root window remains active after a dialog is popped up. In fact, nonmodal dialogs never
block other windows, so you can keep pressing the root’s button to generate as many
copies of the pop-up window as will fit on your screen. Any or all of the pop ups can
be killed by pressing their OK buttons, without killing other windows in this display.
Making custom dialogs modal
Now, when the script is run with a command-line argument (e.g.,
python dlg-custom.py 1), it makes its pop ups modal instead. Because modal dialogs
grab all of the interface’s attention, the main window becomes inactive in this mode
until the pop up is killed; you can’t even click on it to reactivate it while the dialog is
440 | Chapter 8: A tkinter Tour, Part 1