widget.wait_variable(var)
widget.wait_window(win)
widget.wait_visibility(win)
These tools pause the caller until a tkinter variable changes its value, a window is
destroyed, or a window becomes visible. All of these enter a local event loop, such
that the application’s mainloop continues to handle events. Note that var is a tkinter
variable object (discussed earlier), not a simple Python variable. To use for modal
dialogs, first call widget.focus() (to set input focus) and widget.grab() (to make
a window be the only one active).
Although we’ll put some of these to work in examples, we won’t go into exhaustive
details on all of these tools here; see other Tk and tkinter documentation for more
information.
Using Threads with tkinter GUIs
Keep in mind that for many programs, Python’s thread support that we discussed in
Chapter 5 can serve some of the same roles as the tkinter tools listed in the preceding
section and can even make use of them. For instance, to avoid blocking a GUI (and its
users) during a long-running file or socket transfer, the transfer can simply be run in a
spawned thread, while the rest of the program continues to run normally. Similarly,
GUIs that must watch for inputs on pipes or sockets can do so in spawned threads or
after callbacks, or some combination thereof, without blocking the GUI itself.
If you do use threads in tkinter programs, however, you need to remember that only
the main thread (the one that built the GUI and started the mainloop) should generally
make GUI calls. At the least, multiple threads should not attempt to update the GUI
at the same time. For example, the update method described in the preceding section
has historically caused problems in threaded GUIs—if a spawned thread calls this
method (or calls a method that does), it can sometimes trigger very strange and even
spectacular program crashes.
In fact, for a simple and more vivid example of the lack of thread safety in tkinter GUIs,
see and run the following files in the book examples distribution package:
...\PP4E\Gui\Tour\threads-demoAll-frm.py
...\PP4E\Gui\Tour threads-demoAll-win.py
These scripts are takeoffs of the prior chapter’s Examples 8-32 and 8-33, which run the
construction of four GUI demo components in parallel threads. They also both crash
horrifically on Windows and require forced shutdown of the program. While some
GUI operations appear to be safe to perform in parallel threads (e.g., see the canvas
moves in Example 9-32), thread safety is not guaranteed by tkinter in general. (For
further proof of tkinter’s lack of thread safety, see the discussion of threaded update
loops in the next chapter, just after Example 10-28; a thread there that attempts to pop
up a new window also makes the GUI fail resoundingly.)
584 | Chapter 9: A tkinter Tour, Part 2