of their code is external to this book, we’ll explore enough of their structure to help
you study them in the examples distribution package.
Two notes before we begin: first, be sure to read the code listings in this chapter for
details we won’t present in the narrative. Second, although small examples that apply
in this chapter’s techniques will show up along the way, more realistic application will
have to await more realistic programs. We’ll put these techniques to use in the larger
examples in the next chapter and throughout the rest of the book. In fact, we’ll be
reusing the modules we develop here often, as tools in other programs in this book;
reusable software wants to be reused. First, though, let’s do what our species does best
and build some tools.
GuiMixin: Common Tool Mixin Classes
If you read the last three chapters, you probably noticed that the code used to construct
nontrivial GUIs can become long if we make each widget by hand. Not only do we have
to link up all the widgets manually, but we also need to remember and then set dozens
of options. If we stick to this strategy, GUI programming often becomes an exercise in
typing, or at least in cut-and-paste text editor operations.
Widget Builder Functions
Instead of performing each step by hand, a better idea is to wrap or automate as much
of the GUI construction process as possible. One approach is to code functions that
provide typical widget configurations, and automate the construction process for cases
to which they apply. For instance, we could define a button function to handle con-
figuration and packing details and support most of the buttons we draw. Exam-
ple 10-1 provides a handful of such widget builder calls.
Example 10-1. PP4E\Gui\Tools\widgets.py
"""
###############################################################################
wrap up widget construction in functions for easier use, based upon some
assumptions (e.g., expansion); use **extras fkw args for width, font/color,
etc., and repack result manually later to override defaults if needed;
###############################################################################
"""
from tkinter import *
def frame(root, side=TOP, extras):
widget = Frame(root)
widget.pack(side=side, expand=YES, fill=BOTH)
if extras: widget.config(extras)
return widget
598 | Chapter 10: GUI Coding Techniques