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

(yzsuai) #1

Figure 19-4. PyCalc calculator at work on Windows 7


If you do run this, you’ll notice that PyCalc implements a normal calculator model—
expressions are evaluated as entered, not all at once at the end. That is, parts of an
expression are computed and displayed as soon as operator precedence and manually
typed parentheses allow. The result in Figure 19-4, for instance, reflects pressing “2”,
and then repeatedly pressing “*” to display successive powers of 2. I’ll explain how this
evaluation works in a moment.


PyCalc’s CalcGui class builds the GUI interface as frames of buttons much like the
simple calculator of the previous section, but PyCalc adds a host of new features.
Among them are another row of action buttons, inherited methods from GuiMixin
(presented in Chapter 10), a new “cmd” button that pops up nonmodal dialogs for
entry of arbitrary Python code, and a recent calculations history pop up. Figure 19-5
captures some of PyCalc’s pop-up windows.


You may enter expressions in PyCalc by clicking buttons in the GUI, typing full ex-
pressions in command-line pop ups, or typing keys on your keyboard. PyCalc intercepts
key press events and interprets them the same as corresponding button presses; typing



  • is like pressing the + button, the Space bar key is “clear,” Enter is “eval,” backspace
    erases a character, and? is like pressing “help.”


The command-line pop-up windows are nonmodal (you can pop up as many as you
like). They accept any Python code—press the Run button or your Enter key to evaluate
text in their input fields. The result of evaluating this code in the calculator’s namespace


1464 | Chapter 19: Text and Language

Free download pdf