Python Programming: An Introduction to Computer Science

(Nora) #1
192 CHAPTER11. DATA COLLECTIONS

def __createDisplay(self):
bg = Rectangle(Point(.5,5.5), Point(5.5,6.5))
bg.setFill(’white’)
bg.draw(self.win)
text = Text(Point(3,6),"")
text.draw(self.win)
text.setFace("courier")
text.setStyle("bold")
text.setSize(16)
self.display= text

def getKeyPress(self):
# Waits for a buttonto be clicked and returns the labelof
# the buttonthe was clicked.
while 1:
p = self.win.getMouse()
for b in self.buttons:
if b.clicked(p):
returnb.getLabel() # method exit

def processKey(self,key):
# Updates the displayof the calculator for press of thiskey
text = self.display.getText()
if key == ’C’:
self.display.setText("")
elif key == ’<-’:
# Backspace,slice off the last character.
self.display.setText(text[:-1])
elif key == ’=’:
# Evaluatethe expresssion and display the result.
# the try...exceptmechanism "catches" errors in the
# formulabeing evaluated.
try:
result = eval(text)
except:
result = ’ERROR’
self.display.setText(str(result))
else:
# Normal key press,append it to the end of the display
self.display.setText(text+key)

def run(self):
# Infinite’event loop’ to process key presses.
while 1:
key = self.getKeyPress()
self.processKey(key)

This runs the program.


if name == "main":


First createa calculator object


theCalc = Calculator()


Now call the calculator’srun method.


theCalc.run()

Free download pdf