Skip to Main Content
Programming Python, 3rd Edition
book

Programming Python, 3rd Edition

by Mark Lutz
August 2006
Intermediate to advanced content levelIntermediate to advanced
1600 pages
51h 46m
English
O'Reilly Media, Inc.
Content preview from Programming Python, 3rd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python, 3rd Edition

Learning Python, 3rd Edition

Mark Lutz

Publisher Resources

ISBN: 0596009259Supplemental ContentErrata Page