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

(yzsuai) #1
In Chapter 8, we’ll meet two exceptions to this rule. Scripts must man-
ually retain a reference to image objects because the underlying image
data is discarded if the Python image object is garbage collected. tkinter
variable class objects also temporarily unset an associated Tk variable if
reclaimed, but this is uncommon and less harmful.

Adding Buttons and Callbacks


So far, we’ve learned how to display messages in labels, and we’ve met tkinter core
concepts along the way. Labels are nice for teaching the basics, but user interfaces
usually need to do a bit more...like actually responding to users. To show how, the
program in Example 7-10 creates the window in Figure 7-5.


Example 7-10. PP4E\Gui\Intro\gui2.py


import sys
from tkinter import *
widget = Button(None, text='Hello widget world', command=sys.exit)
widget.pack()
widget.mainloop()


Figure 7-5. A button on the top


Here, instead of making a label, we create an instance of the tkinter Button class. It’s
attached to the default top level window as before on the default TOP packing side. But
the main thing to notice here is the button’s configuration arguments: we set an option
called command to the sys.exit function.


For buttons, the command option is the place where we specify a callback handler func-
tion to be run when the button is later pressed. In effect, we use command to register an
action for tkinter to call when a widget’s event occurs. The callback handler used here
isn’t very interesting: as we learned in Chapter 5, the built-in sys.exit function simply
shuts down the calling program. Here, that means that pressing this button makes the
window go away.


Just as for labels, there are other ways to code buttons. Example 7-11 is a version that
packs the button in place without assigning it to a name, attaches it to the LEFT side of
its parent window explicitly, and specifies root.quit as the callback handler—a stand-
ard Tk object method that shuts down the GUI and so ends the program. Technically,
quit ends the current mainloop event loop call, and thus the entire program here; when


Adding Buttons and Callbacks| 379
Free download pdf