Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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()