Adding Multiple Widgets

It’s time to start building user interfaces with more than one widget. Example 8-17 makes the window shown in Figure 8-14.

A multiple-widget window

Figure 8-14. A multiple-widget window

Example 8-17. PP3E\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( )

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 argument. 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:\...\PP3E\Gui\Intro>python gui4.py
Hello stdout world!...
Hello stdout world!...
Hello stdout world!...
Hello stdout world!...

The notion of attaching widgets to containers turns out to be at the core ...

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.