In more complex displays, such a button will expand only if all of the widgets it is
contained by are set to expand too. Here, the button’s only parent is the Tk root window
of the program, so parent expandability isn’t yet an issue; in later examples, we’ll need
to make enclosing Frame widgets expandable too. We will revisit the packer geometry
manager when we meet multiple-widget displays that use such devices later in this
tutorial, and again when we study the alternative grid call in Chapter 9.
Adding User-Defined Callback Handlers
In the simple button examples in the preceding section, the callback handler was simply
an existing function that killed the GUI program. It’s not much more work to register
callback handlers that do something a bit more useful. Example 7-12 defines a callback
handler of its own in Python.
Example 7-12. PP4E\Gui\Intro\gui3.py
import sys
from tkinter import *
def quit(): # a custom callback handler
print('Hello, I must be going...') # kill windows and process
sys.exit()
widget = Button(None, text='Hello event world', command=quit)
widget.pack()
widget.mainloop()
The window created by this script is shown in Figure 7-11. This script and its GUI are
almost identical to the last example. But here, the command option specifies a function
we’ve defined locally. When the button is pressed, tkinter calls the quit function in this
file to handle the event, passing it zero arguments. Inside quit, the print call statement
types a message on the program’s stdout stream, and the GUI process exits as before.
Figure 7-11. A button that runs a Python function
As usual, stdout is normally the window that the program was started from unless it’s
been redirected to a file. It’s a pop-up DOS console if you run this program by clicking
it on Windows; add an input call before sys.exit if you have trouble seeing the message
before the pop up disappears. Here’s what the printed output looks like back in
standard stream world when the button is pressed; it is generated by a Python function
called automatically by tkinter:
382 | Chapter 7: Graphical User Interfaces