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

(yzsuai) #1

The two extensions in this script are artificial, of course—they simply add labels at the
top and bottom of the window—but the concept is widely applicable. You could reuse
the calculator’s class by attaching it to any GUI that needs a calculator and customize
it with subclasses arbitrarily. It’s a reusable widget.


Adding new buttons in new components


One obvious way to reuse the calculator is to add additional expression feature
buttons—square roots, inverses, cubes, and the like. You can type such operations in
the command-line pop ups, but buttons are a bit more convenient. Such features could
also be added to the main calculator implementation itself, but since the set of features
that will be useful may vary per user and application, a better approach may be to add
them in separate extensions. For instance, the class in Example 19-22 adds a few extra
buttons to PyCalc by embedding (i.e., attaching) it in a container.


Example 19-22. PP4E\Lang\Calculator\calculator_plus_emb.py


"""
#############################################################################
a container with an extra row of buttons for common operations;
a more useful customization: adds buttons for more operations (sqrt,
1/x, etc.) by embedding/composition, not subclassing; new buttons are
added after entire CalGui frame because of the packing order/options;
#############################################################################
"""


from tkinter import *
from calculator import CalcGui, getCalcArgs
from PP4E.Gui.Tools.widgets import frame, button, label


class CalcGuiPlus(Toplevel):
def init(self, args):
Toplevel.init(self)
label(self, TOP, 'PyCalc Plus - Container')
self.calc = CalcGui(self,
args)
frm = frame(self, BOTTOM)
extras = [('sqrt', 'sqrt(%s)'),
('x^2 ', '(%s)2'),
('x^3 ', '(%s)
3'),
('1/x ', '1.0/(%s)')]
for (lab, expr) in extras:
button(frm, LEFT, lab, (lambda expr=expr: self.onExtra(expr)))
button(frm, LEFT, ' pi ', self.onPi)


def onExtra(self, expr):
text = self.calc.text
eval = self.calc.eval
try:
text.set(eval.runstring(expr % text.get()))
except:
text.set('ERROR')


PyCalc: A Calculator Program/Object | 1477
Free download pdf