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

(yzsuai) #1

text.set("ERROR") # bad as statement too?
else:
text.set('') # worked as a statement
except:
text.set("ERROR") # other eval expression errors


if name == 'main': CalcGui().mainloop()


Figure 19-2. The calc0 script in action on Windows 7 (result=160.283)


Building the GUI


Now, this is about as simple as a calculator can be, but it demonstrates the basics. This
window comes up with buttons for entry of numbers, variable names, and operators.
It is built by attaching buttons to frames: each row of buttons is a nested Frame, and
the GUI itself is a Frame subclass with an attached Entry and six embedded row frames
(grids would work here, too). The calculator’s frame, entry field, and buttons are made
expandable in the imported widgets utility module we coded earlier in Example 10-1.


This calculator builds up a string to pass to the Python interpreter all at once on “eval”
button presses. Because you can type any Python expression or statement in the entry
field, the buttons are really just a convenience. In fact, the entry field isn’t much more
than a command line. Try typing import sys, and then dir(sys) to display sys module
attributes in the input field at the top—it’s not what you normally do with a calculator,
but it is demonstrative nevertheless.*



  • Once again, I need to warn you about running code strings like this if you can’t be sure they won’t cause
    damage. If these strings can be entered by users you cannot trust, they will have access to anything on the
    computer that the Python process has access to. See Chapters 9 and 15 for more on security issues related to
    code run in GUI, Web, and other contexts.


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