O'Reilly logo

Programming Python, 3rd Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required