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 8-12 defines a callback handler of its own in Python.

Example 8-12. PP3E\Gui\Intro\gui3.py

from Tkinter import *

def quit( ):                                  # a custom callback handler
    print 'Hello, I must be going...'          # kill windows and process
    import sys; 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 8-13. 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 statement types a message on the program’s stdout stream, and the GUI process exits as before.

A button that runs a Python function

Figure 8-13. 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 a raw_input call before sys.exit if you have trouble seeing the message before the pop up disappears. Here’s what the ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.