Python Programming: An Introduction to Computer Science

(Nora) #1
190 CHAPTER11. DATA COLLECTIONS

self.buttons.append(Button(self.win, Point(4.5,1), 1.75,.75, "="))

I couldhave writtena linelike thisforeachofthepreviousbuttons,butI thinkyoucanseetheappealofthe
specification-list/loopapproachforcreatingtheseventeensimilarbuttons.
Incontrasttothebuttons,creatingthecalculatordisplayisquitesimple. Thedisplaywilljustbea
rectanglewithsometextcenteredonit.We needtosave thetextobjectasaninstancevariablesothatits
contentscanbeaccessedandchangedduringprocessingofbuttonclicks.Hereis thecodethatcreatesthe
display:


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

11.5.3 ProcessingButtons


Nowthatwehave aninterfacedrawn,weneeda methodthatactuallygetsthecalculatorrunning. Our
calculatorwillusea classiceventloopthatwaitsfora buttontobeclickedandthenprocessesthatbutton.
Let’s encapsulatethisina methodcalledrun.


def run(self):
while 1:
key = self.getKeyPress()
self.processKey(key)

Noticethatthisis aninfiniteloop.To quittheprogram,theuserwillhave to“kill”thecalculatorwindow. All
that’s leftis toimplementthegetKeyPressandprocessKeymethods.
Gettingkey pressesiseasy;wecontinuegettingmouseclicksuntiloneofthosemouseclicksisona
button.To determinewhethera buttonhasbeenclicked,weloopthroughthelistofbuttonsandcheckeach
one.Theresultis a nestedloop.


def getKeyPress(self):
# Waits for a buttonto be clicked
# RETURNS the labelof the button the was clicked.
while 1:
# loop foreach mouse click
p = self.win.getMouse()
for b in self.buttons:
# loop for eachbutton
if b.clicked(p):
returnb.getLabel() # method exit

Youcanseehowhavingthebuttonsina listisa bigwinhere. We canuseafor looptolookateach
buttoninturn.If theclickedpointpturnsouttobeinoneofthebuttons,thelabelofthatbuttonis returned,
providinganexitfromtheotherwiseinfinitewhileloop.
Thelaststepis toupdatethedisplayofthecalculatoraccordingtowhichbuttonwasclicked. Thisis
accomplishedinprocessKey. Basically, thisis a multi-waydecisionthatchecksthekey labelandtakes
theappropriateaction.
A digitoroperatoris simplyappendedtothedisplay. Ifkeycontainsthelabelofthebutton,andtext
containsthecurrentcontentsofthedisplay, theappropriatelineofcodelookslike this:


self.display.setText(text+key)
Free download pdf