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
stdout stream, and the
GUI process exits as before.
Figure 7-11. A button that runs a Python function
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 ...