This code is something of a preview; see file gui5b-themed.py in the examples package
for a complete version, and watch for more on its widget configuration options in
Chapter 8. But it illustrates the application of common appearance by subclassing
widgets directly—every button created from its class looks the same, and will pick up
any future changes in its configurations automatically.
Widget subclasses are a programmer’s tool, of course, but we can also make such con-
figurations accessible to a GUI’s users. In larger programs later in the book (e.g., PyEdit,
PyClock, and PyMailGUI), we’ll sometimes achieve a similar effect by importing con-
figurations from modules and applying them to widgets as they are built. If such ex-
ternal settings are used by a customized widget subclass like our ThemedButton above,
they will again apply to all its instances and subclasses (for reference, the full version
of the following code is in file gui5b-themed-user.py):
from user_preferences import bcolor, bfont, bsize # get user settings
class ThemedButton(Button):
def __init__(self, parent=None, **configs):
Button.__init__(self, parent, **configs)
self.pack()
self.config(bg=bcolor, font=(bfont, bsize))
ThemedButton(text='spam', command=onSpam) # normal button widget objects
ThemedButton(text='eggs', command=onEggs) # all inherit user preferences
class MyButton(ThemedButton): # subclasses inherit prefs too
def __init__(self, parent=None, **configs):
ThemedButton.__init__(self, parent, **configs)
self.config(text='subclass')
MyButton(command=onSpam)
Again, more on widget configuration in the next chapter; the big picture to take away
here is that customizing widget classes with subclasses allows us to tailor both their
behavior and their appearance for an entire set of widgets. The next example provides
yet another way to arrange for specialization—as customizable and attachable widget
packages, usually known as components.
Reusable GUI Components with Classes
Larger GUI interfaces are often built up as subclasses of Frame, with callback handlers
implemented as methods. This structure gives us a natural place to store information
between events: instance attributes record state. It also allows us to both specialize
GUIs by overriding their methods in new subclasses and attach them to larger GUI
structures to reuse them as general components. For instance, a GUI text editor im-
plemented as a Frame subclass can be attached to and configured by any number of
other GUIs; if done well, we can plug such a text editor into any user interface that
needs text editing tools.
Reusable GUI Components with Classes | 403