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

(yzsuai) #1
C:\...\PP4E\Gui\Intro> python gui3.py
Hello, I must be going...

C:\...\PP4E\Gui\Intro>

Normally, such messages would be displayed in the GUI, but we haven’t gotten far
enough to know how just yet. Callback functions usually do more, of course (and may
even pop up new independent windows altogether), but this example illustrates the
basics.


In general, callback handlers can be any callable object: functions, anonymous func-
tions generated with lambda expressions, bound methods of class or type instances, or
class instances that inherit a call operator overload method. For Button press call-
backs, callback handlers always receive no arguments (other than an automatic self,
for bound methods); any state information required by the callback handler must be
provided in other ways—as global variables, class instance attributes, extra arguments
provided by an indirection layer, and so on.


To make this a bit more concrete, let’s take a quick look at some other ways to code
the callback handler in this example.


Lambda Callback Handlers


Recall that the Python lambda expression generates a new, unnamed function object
when run. If we need extra data passed in to the handler function, we can register
lambda expressions to defer the call to the real handler function, and specify the extra
data it needs.


Later in this part of the book, we’ll see how this can be more useful, but to illustrate
the basic idea, Example 7-13 shows what Example 7-12 looks like when recoded to use
a lambda instead of a def.


Example 7-13. PP4E\Gui\Intro\gui3b.py


import sys
from tkinter import * # lambda generates a function


widget = Button(None, # but contains just an expression
text='Hello event world',
command=(lambda: print('Hello lambda world') or sys.exit()) )


widget.pack()
widget.mainloop()


This code is a bit tricky because lambdas can contain only an expression; to emulate
the original script, this version uses an or operator to force two expressions to be run
( print works as the first, because it’s a function call in Python 3.X—we don’t need to
resort to using sys.stdout directly).


Adding User-Defined Callback Handlers | 383
Free download pdf