can be much larger. If you imagine replacing the Hello call in this script with a call to
attach an already coded and fully debugged calculator object, you’ll begin to better
understand the power of this paradigm. If we code all of our GUI components as classes,
they automatically become a library of reusable widgets, which we can combine in other
applications as often as we like.
Extending Class Components
When GUIs are built with classes, there are a variety of ways to reuse their code in other
displays. To extend Hello instead of attaching it, we just override some of its methods
in a new subclass (which itself becomes a specialized Frame widget). This technique is
shown in Example 7-23.
Example 7-23. PP4E\Gui\Intro\gui6d.py
from tkinter import *
from gui6 import Hello
class HelloExtender(Hello):
def make_widgets(self): # extend method here
Hello.make_widgets(self)
Button(self, text='Extend', command=self.quit).pack(side=RIGHT)
def message(self):
print('hello', self.data) # redefine method here
if name == 'main': HelloExtender().mainloop()
This subclass’s make_widgets method here first builds the superclass’s widgets and then
adds a second Extend button on the right, as shown in Figure 7-22.
Figure 7-22. A customized class’s widgets, on the left
Because it redefines the message method, pressing the original superclass’s button on
the left now prints a different string to stdout (when searching up from self, the
message attribute is found first in this subclass, not in the superclass):
C:\...\PP4E\Gui\Intro> python gui6d.py
hello 42
hello 42
hello 42
hello 42
But pressing the new Extend button on the right, which is added by this subclass, exits
immediately, since the quit method (inherited from Hello, which inherits it from
Reusable GUI Components with Classes | 407