Python Programming: An Introduction to Computer Science

(Nora) #1
168 CHAPTER10. DEFININGCLASSES

AsI mentionedabove, inorderforthiscodetowork,ourconstructorwillhave toinitializeself.label
asanapproprateTextobjectandself.rectasaRectangleobject.Inaddition,theself.active
instancevariablestoresa Booleanvalue(1fortrue,0 forfalse)torememberwhetherornotthebuttonis
currentlyactive.
Ourdeactivatemethodwilldotheinverseofactivate. It lookslike this:


def deactivate(self):
"Sets thisbutton to ’inactive’."
self.label.setFill(’darkgrey’)
self.rect.setWidth(1)
self.active= 0

Ofcourse,themainpointofa buttonis beingabletodetermineif it hasbeenclicked.Let’s trytowrite
theclickedmethod.Asyouknow, thegraphicspackageprovidesagetMousemethodthatreturns
thepointwherethemousewasclicked.If anapplicationneedstogeta buttonclick,it willfirsthave tocall
getMouseandthenseewhichactive button(ifany)thepointis insideof.We couldimaginethebutton
processingcodelookingsomethinglike thefollowing:


pt = win.getMouse()
if button1.clicked(pt):


Do button1 stuff


elif button2.clicked(pt):


Do button2 stuff


elif button2.clicked(pt)


Do button3 stuff


...


Themainjoboftheclickedmethodis todeterminewhethera givenpointis insidetherectangular
button.Thepointis insidetherectangleif itsxandycoordinatesliebetweentheextremexandyvalues
oftherectangle. Thiswouldbeeasiesttofigureoutif wejustassumethatthebuttonobjecthasinstance
variablesthatrecordtheminandmaxvaluesofxandy.
Assumingtheexistenceofinstancevariablesxmin,xmax,ymin, andymax, wecanimplementthe
clickedmethodwitha singleBooleanexpression.


def clicked(self,p):
"RETURNS trueif button is active and p is inside"
return self.activeand \
self.xmin<= p.getX() <= self.xmax and \
self.ymin<= p.getY() <= self.ymax

Herewehave a singlelargeBooleanexpressioncomposedbyandingtogetherthreesimplerexpressions;all
threemustbetrueforthefunctiontoreturna truevalue.Recallthatthebackslashat theendofa lineis used
toextenda statementovermultiplelines.
Thefirstofthethreesubexpressionssimplyretrievesthevalueoftheinstancevariableself.active.
Thisensuresthatonlyactive buttonswillreportthatthey have beenclicked.Ifself.activeis false,then
clickedwillreturnfalse.Thesecondtwo subexpressionsarecompoundconditionstocheckthatthexand
yvaluesofthepointfallbetweentheedgesofthebuttonrectangle.(Remember,x <= y <= zmeansthe
sameasthemathematicalexpressionx y z(section7.5.1)).
Now thatwehave thebasicoperationsofthebuttonironedout,wejustneeda constructortogetallthe
instancevariablesproperlyinitialized.It’s nothard,butit is a bittedious.Hereis thecompleteclasswitha
suitableconstructor.


button.py


from graphics import*


class Button:

Free download pdf