enclosing rectangles. As we’ll see later, tkinter arranges widgets in a rectangle according
to both their packing order and their side attachment options. When widgets are grid-
ded, they are assigned row and column numbers instead. None of this will become very
meaningful, though, until we have more than one widget in a window, so let’s move on.
Notice that this version calls the pack method right away after creating the label, without
assigning it a variable. If we don’t need to save a widget, we can pack it in place like
this to eliminate a statement. We’ll use this form when a widget is attached to a larger
structure and never again referenced. This can be tricky if you assign the pack result,
though, but I’ll postpone an explanation of why until we’ve covered a few more basics.
We also use a Tk widget class instance, instead of None, as the parent here. Tk represents
the main (“root”) window of the program—the one that starts when the program does.
An automatically created Tk instance is also used as the default parent widget, both
when we don’t pass any parent to other widget calls and when we pass the parent as
None. In other words, widgets are simply attached to the main program window by
default. This script just makes this default behavior explicit by making and passing the
Tk object itself. In Chapter 8, we’ll see that Toplevel widgets are typically used to gen-
erate new pop-up windows that operate independently of the program’s main window.
In tkinter, some widget methods are exported as functions, and this lets us shave
Example 7-5 to just three lines of code.
Example 7-5. PP4E\Gui\Intro\gui1d.py—a minimal version
from tkinter import *
Label(text='Hello GUI world!').pack()
mainloop()
The tkinter mainloop can be called with or without a widget (i.e., as a function or
method). We didn’t pass Label a parent argument in this version, either: it simply
defaults to None when omitted (which in turn defaults to the automatically created Tk
object). But relying on that default is less useful once we start building larger displays.
Things such as labels are more typically attached to other widget containers.
Widget Resizing Basics
Top-level windows, such as the one built by all of the coding variants we have seen
thus far, can normally be resized by the user; simply drag out the window with your
mouse. Figure 7-2 shows how our window looks when it is expanded.
This isn’t very good—the label stays attached to the top of the parent window instead
of staying in the middle on expansion—but it’s easy to improve on this with a pair of
pack options, demonstrated in Example 7-6.
tkinter Coding Alternatives | 373