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. The program in Example 8-10 creates the window in Figure 8-7.
Figure 8-7. A button on the top
Example 8-10. PP3E\Gui\Intro\gui2.py
import sys from Tkinter import * widget = Button(None, text='Hello widget world', command=sys.exit) widget.pack( ) widget.mainloop( )
Here, instead of making a label, we create an instance of the
Button class. It's attached
to the default top level 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
command to the
For buttons, the
option is the place where we specify a callback handler function 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 an earlier chapter, the
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 8-11 is a version that packs the button in place ...