Making Widgets
When widgets are constructed in tkinter, we can specify how they should be configured.
The gui1 script passes two arguments to the Label class constructor:
- The first is a parent-widget object, which we want the new label to be attached to.
Here, None means “attach the new Label to the default top-level window of this
program.” Later, we’ll pass real widgets in this position to attach our labels to other
container objects. - The second is a configuration option for the Label, passed as a keyword argument:
the text option specifies a text string to appear as the label’s message. Most widget
constructors accept multiple keyword arguments for specifying a variety of options
(color, size, callback handlers, and so on). Most widget configuration options have
reasonable defaults per platform, though, and this accounts for much of tkinter’s
simplicity. You need to set most options only if you wish to do something custom.
As we’ll see, the parent-widget argument is the hook we use to build up complex GUIs
as widget trees. tkinter works on a “what-you-build-is-what-you-get” principle—we
construct widget object trees as models of what we want to see on the screen, and then
ask the tree to display itself by calling mainloop.
Geometry Managers
The pack widget method called by the gui1 script invokes the packer geometry man-
ager, one of three ways to control how widgets are arranged in a window. tkinter ge-
ometry managers simply arrange one or more widgets within a container (sometimes
called a parent or master). Both top-level windows and frames (a special kind of widget
we’ll meet later) can serve as containers, and containers may be nested inside other
containers to build hierarchical displays.
The packer geometry manager uses constraint option settings to automatically position
widgets in a window. Scripts supply higher-level instructions (e.g., “attach this widget
to the top of its container, and stretch it to fill its space vertically”), not absolute pixel
coordinates. Because such constraints are so abstract, the packer provides a powerful
and easy-to-use layout system. In fact, you don’t even have to specify constraints. If
you don’t pass any arguments to pack, you get default packing, which attaches the
widget to the top side of its container.
We’ll visit the packer repeatedly in this chapter and use it in many of the examples in
this book. In Chapter 9, we will also meet an alternative grid geometry manager—a
layout system that arranges widgets within a container in tabular form (i.e., by rows
and columns) and works well for input forms. A third alternative, called the placer
geometry manager system, is described in Tk documentation but not in this book; it’s
less popular than the pack and grid managers and can be difficult to use for larger GUIs
coded by hand.
370 | Chapter 7: Graphical User Interfaces