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

(yzsuai) #1

Common behavior


Example 7-18 standardizes behavior—it allows widgets to be configured by subclassing
instead of by passing in options. In fact, its HelloButton is a true button; we can pass
in configuration options such as its text as usual when one is made. But we can also
specify callback handlers by overriding the callback method in subclasses, as shown
in Example 7-19.


Example 7-19. PP4E\Gui\Intro\gui5b.py


from gui5 import HelloButton


class MyButton(HelloButton): # subclass HelloButton
def callback(self): # redefine press-handler method
print("Ignoring press!...")


if name == 'main':
MyButton(None, text='Hello subclass world').mainloop()


This script makes the same window; but instead of exiting, this MyButton button, when
pressed, prints to stdout and stays up. Here is its standard output after being pressed
a few times:


C:\...\PP4E\Gui\Intro> python gui5b.py
Ignoring press!...
Ignoring press!...
Ignoring press!...
Ignoring press!...

Whether it’s simpler to customize widgets by subclassing or passing in options is prob-
ably a matter of taste in this simple example. But the larger point to notice is that Tk
becomes truly object oriented in Python, just because Python is object oriented—we
can specialize widget classes using normal class-based and object-oriented techniques.
In fact this applies to both widget behavior and appearance.


Common appearance


For example, although we won’t study widget configuration options until the next
chapter, a similar customized button class could provide a standard look-and-feel
different from tkinter’s defaults for every instance created from it, and approach the
notions of “styles” or “themes” in some GUI toolkits:


class ThemedButton(Button): # config my style too
def __init__(self, parent=None, **configs): # used for each instance
Button.__init__(self, parent, **configs) # see chapter 8 for options
self.pack()
self.config(fg='red', bg='black', font=('courier', 12), relief=RAISED, bd=5)

B1 = ThemedButton(text='spam', command=onSpam) # normal button widget objects
B2 = ThemedButton(text='eggs') # but same appearance by inheritance
B2.pack(expand=YES, fill=BOTH)

402 | Chapter 7: Graphical User Interfaces

Free download pdf