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

(yzsuai) #1

Coding for reusability


A postscript: I coded the demo launcher bars deployed by the last four examples to
demonstrate all the different ways that their widgets can be used. They were not de-
veloped with general-purpose reusability in mind; in fact, they’re not really useful out-
side the context of introducing widgets in this book.


That was by design; most tkinter widgets are easy to use once you learn their interfaces,
and tkinter already provides lots of configuration flexibility by itself. But if I had it in
mind to code checkbutton and radiobutton classes to be reused as general library com-
ponents, they would have to be structured differently:


Extra widgets
They would not display anything but radio buttons and check buttons. As is, the
demos each embed State and Quit buttons for illustration, but there really should
be just one Quit per top-level window.


Geometry management
They would allow for different button arrangements and would not pack (or grid)
themselves at all. In a true general-purpose reuse scenario, it’s often better to leave
a component’s geometry management up to its caller.


Usage mode limitations
They would either have to export complex interfaces to support all possible tkinter
configuration options and modes, or make some limiting decisions that support
one common use only. For instance, these buttons can either run callbacks at press
time or provide their state later in the application.


Example 8-36 shows one way to code check button and radio button bars as library
components. It encapsulates the notion of associating tkinter variables and imposes a
common usage mode on callers—state fetches rather than press callbacks—to keep the
interface simple.


Example 8-36. PP4E\Gui\Tour\buttonbars.py


"""
check and radio button bar classes for apps that fetch state later;
pass a list of options, call state(), variable details automated
"""


from tkinter import *


class Checkbar(Frame):
def init(self, parent=None, picks=[], side=LEFT, anchor=W):
Frame.init(self, parent)
self.vars = []
for pick in picks:
var = IntVar()
chk = Checkbutton(self, text=pick, variable=var)
chk.pack(side=side, anchor=anchor, expand=YES)
self.vars.append(var)
def state(self):


482 | Chapter 8: A tkinter Tour, Part 1

Free download pdf