Hiding and redrawing widgets and windows
The button flash method flashes the widget, but it’s easy to dynamically change other
appearance options of widgets, such as buttons, labels, and text, with the widget
config method. For instance, you can also achieve a flash-like effect by manually re-
versing foreground and background colors with the widget config method in scheduled
after callbacks. Largely for fun, Example 9-28 specializes the alarm to go a step further.
Example 9-28. PP4E\Gui\Tour\alarm-hide.py
customize to erase or show button on after() timer callbacks
from tkinter import *
import alarm
class Alarm(alarm.Alarm): # change alarm callback
def init(self, msecs=1000): # default = 1 second
self.shown = False
alarm.Alarm.init(self, msecs)
def repeater(self): # on every N millisecs
self.bell() # beep now
if self.shown:
self.stopper.pack_forget() # hide or erase button now
else: # or reverse colors, flash...
self.stopper.pack()
self.shown = not self.shown # toggle state for next time
self.after(self.msecs, self.repeater) # reschedule handler
if name == 'main': Alarm(msecs=500).mainloop()
When this script is run, the same window appears, but the button is erased or redrawn
on alternating timer events. The widget pack_forget method erases (unmaps) a drawn
widget and pack makes it show up again; grid_forget and grid similarly hide and show
widgets in a grid. The pack_forget method is useful for dynamically drawing and
changing a running GUI. For instance, you can be selective about which components
are displayed, and you can build widgets ahead of time and show them only as needed.
Here, it just means that users must press the button while it’s displayed, or else the
noise keeps going.
Example 9-29 goes even further. There are a handful of methods for hiding and un-
hiding entire top-level windows:
- To hide and unhide the entire window instead of just one widget within it, use
the top-level window widget withdraw and deiconify methods. The withdraw
method, demonstrated in Example 9-29, completely erases the window and its icon
(use iconify if you want the window’s icon to appear during a hide). - The lift method raises a window above all its siblings or relative to another you
pass in. This method is also known as tkraise, but not raise—its name in Tk—
because raise is a reserved word in Python.
Time Tools, Threads, and Animation | 587