expand=YES option
Asks the packer to expand the allocated space for the widget in general into any
unclaimed space in the widget’s parent.
fill option
Can be used to stretch the widget to occupy all of its allocated space.
Combinations of these two options produce different layout and resizing effects, some
of which become meaningful only when there are multiple widgets in a window. For
example, using expand without fill centers the widget in the expanded space, and the
fill option can specify vertical stretching only (fill=Y), horizontal stretching only
(fill=X), or both (fill=BOTH). By providing these constraints and attachment sides for
all widgets in a GUI, along with packing order, we can control the layout in fairly precise
terms. In later chapters, we’ll find that the grid geometry manager uses a different
resizing protocol entirely, but it provides similar control when needed.
All of this can be confusing the first time you hear it, and we’ll return to this later. But
if you’re not sure what an expand and fill combination will do, simply try it out—this
is Python, after all. For now, remember that the combination of expand=YES and
fill=BOTH is perhaps the most common setting; it means “expand my space allocation
to occupy all available space on my side, and stretch me to fill the expanded space in
both directions.” For our “Hello World” example, the net result is that the label grows
as the window is expanded, and so is always centered.
Configuring Widget Options and Window Titles
So far, we’ve been telling tkinter what to display on our label by passing its text as a
keyword argument in label constructor calls. It turns out that there are two other ways
to specify widget configuration options. In Example 7-7, the text option of the label is
set after it is constructed, by assigning to the widget’s text key. Widget objects overload
(intercept) index operations such that options are also available as mapping keys, much
like a dictionary.
Example 7-7. PP4E\Gui\Intro\gui1f.py—option keys
from tkinter import *
widget = Label()
widget['text'] = 'Hello GUI world!'
widget.pack(side=TOP)
mainloop()
More commonly, widget options can be set after construction by calling the widget
config method, as in Example 7-8.
tkinter Coding Alternatives | 375