11.5. CASESTUDY: PYTHONCALCULATOR 191
Theclearkey blanksthedisplay.
self.display.setText("")
Thebackspacestripsoff onecharacter.
self.display.setText(text[:-1])
Finally, theequalkey causestheexpressioninthedisplaytobeevaluatedandtheresultdisplayed.
try:
result = eval(text)
except:
result = ’ERROR’
self.display.setText(str(result))
Thetry-excepthereisnecessarytocatchrun-timeerrorscausedbyentriesthatarenotlegalPython
expressions.If anerroroccurs,thecalculatorwilldisplayERRORratherthancausingtheprogramtocrash.
Hereis thecompleteprogram.
calc.pyw -- A fourfunction calculator using Python arithmetic.
from graphics import*
from buttons importButton
class Calculator:
This class implementsa simple calculator GUI
def __init__(self):
# create the windowfor the calculator
win = GraphWin("calculator")
win.setCoords(0,0,6,7)
win.setBackground("slategray")
self.win = win
# Now createthe widgets
self.__createButtons()
self.__createDisplay()
def __createButtons(self):
# create listof buttons
# buttonSpecgives center, width and label of a button
buttonSpecs= [(2,1,.75,’0’), (3,1,.75,’.’), (4.5,1,2,’=’),
(1,2,.75,’1’),(1,3,.75,’4’), (1,4,.75,’7’),
(2,2,.75,’2’),(2,3,.75,’5’), (2,4,.75,’8’),
(3,2,.75,’3’),(3,3,.75,’6’), (3,4,.75,’9’),
(4,2,.75,’+’),(4,3,.75,’*’), (4,4,.75,’<-’),
(5,2,.75,’-’),(5,3,.75,’/’), (5,4,.75,’C’)
]
yinc = .75/2.0 # half of a "standard" button height
self.buttons= []
for cx,cy,bwidth,label in buttonSpecs:
xinc = bwidth/2.0
p1 = Point(cx-xinc,cy-yinc)
p2 = Point(cx+xinc,cy+yinc)
b = Button(self.win,p1, p2, label)
b.activate()
self.buttons.append(b)