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 7-18 builds the window in Figure 7-19.
Example 7-18. PP4E\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() # could config style too 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()
Figure 7-19. A button subclass in action
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
Button class, but adds
callback method and constructor
logic to set the
command option to
callback, a bound
method of the instance. When the button is pressed this time, the new
callback method, not
a simple function, is invoked.
**config argument here is assigned unmatched keyword arguments ...