We’ll meet bind and all of the other tkinter event callback handler hooks again in more
detail later in this book. First, though, let’s focus on building GUIs that are larger than
a single button and explore a few other ways to use classes in GUI work.
Adding Multiple Widgets
It’s time to start building user interfaces with more than one widget. Example 7-17
makes the window shown in Figure 7-12.
Example 7-17. PP4E\Gui\Intro\gui4.py
from tkinter import *
def greeting():
print('Hello stdout world!...')
win = Frame()
win.pack()
Label(win, text='Hello container world').pack(side=TOP)
Button(win, text='Hello', command=greeting).pack(side=LEFT)
Button(win, text='Quit', command=win.quit).pack(side=RIGHT)
win.mainloop()
Figure 7-12. A multiple-widget window
This example makes a Frame widget (another tkinter class) and attaches three other
widget objects to it, a Label and two Buttons, by passing the Frame as their first argu-
ment. In tkinter terms, we say that the Frame becomes a parent to the other three
widgets. Both buttons on this display trigger callbacks:
- Pressing the Hello button triggers the greeting function defined within this file,
which prints to stdout again. - Pressing the Quit button calls the standard tkinter quit method, inherited by win
from the Frame class (Frame.quit has the same effect as the Tk.quit we used earlier).
Here is the stdout text that shows up on Hello button presses, wherever this script’s
standard streams may be:
C:\...\PP4E\Gui\Intro> python gui4.py
Hello stdout world!...
Hello stdout world!...
Adding Multiple Widgets| 395