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