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

(yzsuai) #1

instead); the buttons also wrap entry field values in parentheses to sidestep precedence
issues. They could instead convert the entry’s text to a number and do real math, but
Python does all the work automatically when expression strings are run raw.


Also note that the buttons added by these scripts simply operate on the current value
in the entry field, immediately. That’s not quite the same as expression operators ap-
plied with the stacks evaluator (additional customizations are needed to make them
true operators). Still, these buttons prove the point these scripts are out to make—they
use PyCalc as a component, both from the outside and from below.


Finally, to test both of the extended calculator classes, as well as PyCalc configuration
options, the script in Example 19-24 puts up four distinct calculator windows (this is
the script run by PyDemos).


Example 19-24. PP4E\Lang\Calculator\calculator_plusplus.py


#!/usr/local/bin/python
"""
demo all 3 calculator flavors at once
each is a distinct calculator object and window
"""


from tkinter import Tk, Button, Toplevel
import calculator, calculator_plus_ext, calculator_plus_emb


root=Tk()
calculator.CalcGui(Toplevel())
calculator.CalcGui(Toplevel(), fg='white', bg='purple')
calculator_plus_ext.CalcGuiPlus(Toplevel(), fg='gold', bg='black')
calculator_plus_emb.CalcGuiPlus(fg='black', bg='red')
Button(root, text='Quit Calcs', command=root.quit).pack()
root.mainloop()


Figure 19-8 shows the result—four independent calculators in top-level windows
within the same process. The two windows on the right represent specialized reuses of
PyCalc as a component, and the Help dialog appears in the lower right. Although it
may not be obvious in this book, all four use different color schemes; calculator classes
accept color and font configuration options and pass them down the call chain as
needed.


As we learned earlier, these calculators could also be run as independent processes by
spawning command lines with the launchmodes module we met in Chapter 5. In fact,
that’s how the PyGadgets and PyDemos launcher bars run calculators, so see their code
for more details. And as always, read the code and experiment on your own for further
enlightenment; this is Python, after all.


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