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. The program in Example 8-10 creates the window in Figure 8-7.

A button on the top

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 Tkinter 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 called command to the sys.exit function.

For buttons, the command 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 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 8-11 is a version that packs the button in place ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.