[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Scheduled event callbacks
Finally, tkinter scripts can also register callback handlers to be run in special con-
texts, such as timer expirations, input data arrival, and event-loop idle states.
Scripts can also pause for state-change events related to windows and special var-
iables. We’ll meet these event interfaces in more detail near the end of Chapter 9.


Binding Events


Of all the options listed in the prior section, bind is the most general, but also perhaps
the most complex. We’ll study it in more detail later, but to let you sample its flavor
now, Example 7-16 rewrites the prior section’s GUI again to use bind, not the
command keyword, to catch button presses.


Example 7-16. PP4E\Gui\Intro\gui3e.py


import sys
from tkinter import *


def hello(event):
print('Press twice to exit') # on single-left click


def quit(event): # on double-left click
print('Hello, I must be going...') # event gives widget, x/y, etc.
sys.exit()


widget = Button(None, text='Hello event world')
widget.pack()
widget.bind('', hello) # bind left mouse clicks
widget.bind('', quit) # bind double-left clicks
widget.mainloop()


In fact, this version doesn’t specify a command option for the button at all. Instead, it
binds lower-level callback handlers for both left mouse clicks () and double-
left mouse clicks () within the button’s display area. The bind method ac-
cepts a large set of such event identifiers in a variety of formats, which we’ll meet in
Chapter 8.


When run, this script makes the same window as before (see Figure 7-11). Clicking on
the button once prints a message but doesn’t exit; you need to double-click on the
button now to exit as before. Here is the output after clicking twice and double-clicking
once (a double-click fires the single-click callback first):


C:\...\PP4E\Gui\Intro> python gui3e.py
Press twice to exit
Press twice to exit
Press twice to exit
Hello, I must be going...

Although this script intercepts button clicks manually, the end result is roughly the
same; widget-specific protocols such as button command options are really just higher-
level interfaces to events you can also catch with bind.


394 | Chapter 7: Graphical User Interfaces

Free download pdf