Customizing Widgets with Classes

You don’t have to use OOP in Tkinter scripts, but it can definitely help. As we just saw, Tkinter GUIs are built up as class-instance object trees. Here’s another way Python’s OOP features can be applied to GUI models: specializing widgets by inheritance. Example 8-18 builds the window in Figure 8-21.

A button subclass in action

Figure 8-21. A button subclass in action

Example 8-18. PP3E\Gui\Intro\gui5.py

from Tkinter import *

class HelloButton(Button):
    def _ _init_ _(self, parent=None, **config):         # add callback method
        Button._ _init_ _(self, parent, config)          # and pack myself
        self.pack( )
        self.config(command=self.callback)
    def callback(self):                                # default press action
        print 'Goodbye world...'                       # replace in subclasses
        self.quit( )

if _ _name_ _ == '_ _main_ _':
    HelloButton(text='Hello subclass world').mainloop( )

This example isn’t anything special to look at: it just displays a single button that, when pressed, prints a message and exits. But this time, it is a button widget we created on our own. The HelloButton class inherits everything from the Tkinter Button class, but adds a callback method and constructor logic to set the command option to self.callback, a bound method of the instance. When the button is pressed this time, the new widget class’s callback method, not a simple function, is invoked.

The **config argument here is assigned unmatched keyword arguments; they’re passed ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.