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

(yzsuai) #1

PyCalc—A “Real” Calculator GUI


Of course, real calculators don’t usually work by building up expression strings and
evaluating them all at once; that approach is really little more than a glorified Python
command line. Traditionally, expressions are evaluated in piecemeal fashion as they
are entered, and temporary results are displayed as soon as they are computed. Imple-
menting this behavior requires a bit more work: expressions must be evaluated man-
ually and in parts, instead of calling the eval function only once. But the end result is
much more useful and intuitive.


Lesson 5: Reusability Is Power
Though simple, attaching and subclassing the calculator graphically, as shown in Fig-
ure 19-3, illustrates the power of Python as a tool for writing reusable software. By
coding programs with modules and classes, components written in isolation almost
automatically become general-purpose tools. Python’s program organization features
promote reusable code.
In fact, code reuse is one of Python’s major strengths and has been one of the main
themes of this book. Good object-oriented design takes some practice and forethought,
and the benefits of code reuse aren’t apparent immediately. And sometimes we have
good cause to be more interested in a quick fix rather than a future use for the code.
But coding with some reusability in mind can save development time in the long run.
For instance, the handcoded custom parsers shared a scanner, the calculator GUI uses
the widgets module from Chapter 10 we discussed earlier, and the next section will
reuse the GuiMixin class from Chapter 10 as well. Sometimes we’re able to finish part
of a job before we start.

This section presents the implementation of PyCalc, a more realistic Python/tkinter
program that implements such a traditional calculator GUI. It touches on the subject
of text and languages in two ways: it parses and evaluates expressions, and it imple-
ments a kind of stack-based language to perform the evaluation. Although its evaluation
logic is more complex than the simpler calculator shown earlier, it demonstrates ad-
vanced programming techniques and serves as an interesting finale for this chapter.


Running PyCalc


As usual, let’s look at the GUI before the code. You can run PyCalc from the PyGadgets
and PyDemos launcher bars at the top of the examples tree, or by directly running the
file calculator.py listed shortly (e.g., click it in a file explorer, or type it in a shell com-
mand line). Figure 19-4 shows PyCalc’s main window. By default, it shows operand
buttons in black-on-blue (and opposite for operator buttons), but font and color op-
tions can be passed into the GUI class’s constructor method. Of course, that means
gray-on-gray in this book, so you’ll have to run PyCalc yourself to see what I mean.


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