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

(yzsuai) #1

def label(root, side, text, extras):
widget = Label(root, text=text, relief=RIDGE) # default config
widget.pack(side=side, expand=YES, fill=BOTH) # pack automatically
if extras: widget.config(
extras) # apply any extras
return widget


def button(root, side, text, command, extras):
widget = Button(root, text=text, command=command)
widget.pack(side=side, expand=YES, fill=BOTH)
if extras: widget.config(
extras)
return widget


def entry(root, side, linkvar, extras):
widget = Entry(root, relief=SUNKEN, textvariable=linkvar)
widget.pack(side=side, expand=YES, fill=BOTH)
if extras: widget.config(
extras)
return widget


if name == 'main':
app = Tk()
frm = frame(app, TOP) # much less code required here!
label(frm, LEFT, 'SPAM')
button(frm, BOTTOM, 'Press', lambda: print('Pushed'))
mainloop()


This module makes some assumptions about its clients’ use cases, which allows it to
automate typical construction chores such as packing. The net effect is to reduce the
amount of code required of its importers. When run as a script, Example 10-1 creates
a simple window with a ridged label on the left and a button on the right that prints a
message when pressed, both of which expand along with the window. Run this on your
own for a look; its window isn’t really anything new for us, and its code is meant more
as library than script—as we’ll see when we make use of it later in Chapter 19’s PyCalc.


This function-based approach can cut down on the amount of code required. As func-
tions, though, its tools don’t lend themselves to customization in the broader OOP
sense. Moreover, because they are not methods, they do not have access to the state of
an object representing the GUI.


Mixin Utility Classes


Alternatively, we can implement common methods in a class and inherit them every-
where they are needed. Such classes are commonly called mixin classes because their
methods are “mixed in” with other classes. Mixins serve to package generally useful
tools as methods. The concept is almost like importing a module, but mixin classes can
access the subject instance, self, to utilize both per-instance state and inherited meth-
ods. The script in Example 10-2 shows how.


GuiMixin: Common Tool Mixin Classes | 599
Free download pdf