[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
Frame) is the added button’s callback handler. The net effect is that this class customizes
the original to add a new button and change message’s behavior.
Although this example is simple, it demonstrates a technique that can be powerful in
practice: to change a GUI’s behavior, we can write a new class that customizes its parts
rather than changing the existing GUI code in place. The main code need be debugged
only once and can be customized with subclasses as unique needs arise.
The moral of this story is that tkinter GUIs can be coded without ever writing a single
new class, but using classes to structure your GUI code makes it much more reusable
in the long run. If done well, you can both attach already debugged components to new
interfaces and specialize their behavior in new external subclasses as needed for custom
requirements. Either way, the initial upfront investment to use classes is bound to save
coding time in the end.

Standalone Container Classes


Before we move on, I want to point out that it’s possible to reap most of the class-based
component benefits previously mentioned by creating standalone classes not derived
from tkinter Frames o r o t h e r w i d g e t s. F o r i n s t a n c e , t h e c l a s s i n Example 7-24 generates
the window shown in Figure 7-23.

Example 7-24. PP4E\Gui\Intro\gui7.py
from tkinter import *

class HelloPackage: # not a widget subbclass
def __init__(self, parent=None):
self.top = Frame(parent) # embed a Frame
self.top.pack()
self.data = 0
self.make_widgets() # attach widgets to self.top

def make_widgets(self):
Button(self.top, text='Bye', command=self.top.quit).pack(side=LEFT)
Button(self.top, text='Hye', command=self.message).pack(side=RIGHT)

def message(self):
self.data += 1
print('Hello number', self.data)

if __name__ == '__main__': HelloPackage().top.mainloop()

Figure 7-23. A standalone class package in action

408 | Chapter 7: Graphical User Interfaces

Do


wnload from Wow! eBook <www.wowebook.com>

Free download pdf