Skip to Main Content
Programming Python, 3rd Edition
book

Programming Python, 3rd Edition

by Mark Lutz
August 2006
Intermediate to advanced content levelIntermediate to advanced
1600 pages
51h 46m
English
O'Reilly Media, Inc.
Content preview from Programming Python, 3rd Edition

Tkinter Coding Alternatives

As you might expect, there are a variety of ways to code the gui1 example. For instance, if you want to make all your Tkinter imports more explicit in your script, grab the whole module and prefix all of its names with the module’s name, as in Example 8-3.

Example 8-3. PP3E\Gui\Intro\gui1b.py—import versus from

import Tkinter
widget = Tkinter.Label(None, text='Hello GUI world!')
widget.pack( )
widget.mainloop( )

That will probably get tedious in realistic examples, though—Tkinter exports dozens of widget classes and constants that show up all over Python GUI scripts. In fact, it is usually easier to use a * to import everything from the Tkinter module by name in one shot. This is demonstrated in Example 8-4.

Example 8-4. PP3E\Gui\Intro\gui1c.py—roots, sides, pack in place

from Tkinter import *
root = Tk( )
Label(root, text='Hello GUI world!').pack(side=TOP)
root.mainloop( )

The Tkinter module goes out of its way to export only what we really need, so it’s one of the few for which the * import form is relatively safe to apply.[*] The TOP constant in the pack call here, for instance, is one of those many names exported by the Tkinter module. It’s simply a variable name (TOP="top") preassigned in Tkconstants, a module automatically loaded by Tkinter.

When widgets are packed, we can specify which side of their parent they should be attached to—TOP, BOTTOM, LEFT, or RIGHT. If no side option is sent to pack (as in prior examples), a widget is attached to its parent’s ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python, 3rd Edition

Learning Python, 3rd Edition

Mark Lutz

Publisher Resources

ISBN: 0596009259Supplemental ContentErrata Page