Python Programming: An Introduction to Computer Science

(Nora) #1
11.5. CASESTUDY: PYTHONCALCULATOR 189

def __init__(self):
# create the windowfor the calculator
win = GraphWin("Calculator")
win.setCoords(0,0,6,7)
win.setBackground("slategray")
self.win = win

Thecoordinatesforthewindow werechosento simplifythelayoutofthebuttons.Inthelastline,thewindow
objectis tuckedintoaninstancevariablesothatothermethodscanrefertoit.
Thenextstepis tocreatethebuttons.We willreusethebuttonclassfromlastchapter. Sincetherearea
lotofsimilarbuttons,wewillusea listtostorethem.Hereis thecodethatcreatesthebuttonlist:


create listof buttons


start withall the standard sized buttons


bSpecs givescenter coords and label of buttons


bSpecs = [(2,1,’0’),(3,1,’.’),
(1,2,’1’),(2,2,’2’), (3,2,’3’), (4,2,’+’),(5,2,’-’),
(1,3,’4’),(2,3,’5’), (3,3,’6’), (4,3,’*’),(5,3,’/’),
(1,4,’7’),(2,4,’8’), (3,4,’9’), (4,4,’<-’),(5,4,’C’)]
self.buttons= []
for cx,cy,labelin bSpecs:
self.buttons.append(Button(self.win,Point(cx,cy),.75,.75,label))


create the larger’=’ button


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


activate allbuttons


for b in self.buttons:
b.activate()
Studythiscodecarefully. Abuttonis normallyspecifiedbyprovidinga centerpoint,width,heightand
label.TypingoutcallstotheButtonconstructorwithallthisinformationforeachbuttonwouldbetedious.
Ratherthancreatingthebuttonsdirectly, thiscodefirstcreatesa listofbuttonspecifications,bSpecs. This
listofspecificationsis thenusedtocreatethebuttons.
Eachspecificationis atupleconsistingofthexandycoordinatesofthecenterofthebuttonanditslabel.
A tuplelookslike a listexceptthatit is enclosedinroundparentheses()insteadofsquarebrackets[]. A
tupleis justanotherkindofsequenceinPython.Tuplesarelike listsexceptthattuplesareimmutable—the
itemscan’t bechanged.If thecontentsofa sequencewon’t bechangedafterit is created,usinga tupleis
moreefficientthanusinga list.
Thenextstepis toiteratethroughthespecificationlistandcreatea correspondingbuttonforeachentry.
Take a lookat theloopheading:


for (cx,cy,label)in bSpecs:

Accordingto thedefinitionofaforloop,thetuple(cx,cy,label)willbeassignedeachsuccessive item
inthelistbSpecs.
Putanotherway, conceptually, eachiterationoftheloopstartswithanassignment.


(cx,cy,label) =


Ofcourse,eachiteminbSpecsis alsoa tuple. Whena tupleofvariablesisusedontheleftsideofan
assignment,thecorrespondingcomponentsofthetupleontherightsideareunpackedintothevariableson
theleftside.Infact,thisis how Pythonactuallyimplementsallsimultaneousassignments.
Thefirsttimethroughtheloop,it is asif wehaddonethissimultaneousassignment:


cx, cy, label = 2, 1, "0"


Eachtimethroughtheloop,anothertuplefrombSpecsis unpackedintothevariablesintheloopheading.
ThevaluesarethenusedtocreateaButtonthatis appendedtothelistofbuttons.
Afterallofthestandard-sizedbuttonshave beencreated,thelarger=buttonis createdandtackedonto
thelist.

Free download pdf