10.5. WIDGETOBJECTS 167
Figure10.3:Snapshotofdicerollerinaction.
themousewasclickedaftertheclickhasalreadycompleted. Nevertheless,wecanmake a useful,if less
pretty, buttonclass.
Ourbuttonswillberectangularregionsin a graphicswindow whereuserclickscaninfluencethebehavior
oftherunningapplication.We willneedtocreatebuttonsanddeterminewhenthey have beenclicked.In
addition,it is alsonicetobeabletoactivateanddeactivateindividualbuttons.Thatway, ourapplicationscan
signalwhichoptionsareavailableto theuserat any givenmoment.Typically, aninactive buttonis grayed-out
toshow thatit is notavailable.
Summarizingthisdescription,ourbuttonswillsupportthefollowingmethods:
constructorCreatea buttonina window. We willhave tospecifythewindow inwhichthebuttonwillbe
displayed,thelocation/sizeofthebutton,andthelabelthatwillbeonthebutton.
activateSetthestateofthebuttontoactive.
deactivateSetthestateofthebuttontoinactive.
clickedIndicateif thebuttonwasclicked.If thebuttonis active,thismethodwilldetermineif thepoint
clickedis insidethebuttonregion.Thepointwillhave tobesentasa parametertothemethod.
getLabelReturnsthelabelstringofthebutton.Thisis providedsothatwecanidentifya particularbutton.
Inordertosupporttheseoperations,ourbuttonswillneeda numberofinstancevariables.Forexample,
thebuttonitselfwillbedrawnasa rectanglewithsometextcenteredinit. Invokingtheactivateand
deactivatemethodswillchangetheappearanceofthebutton.SavingtheRectangleandTextobjects
asinstancevariableswillallowustochangethewidthoftheoutlineandthecolorofthelabel.We might
startbyimplementingthevariousmethodstoseewhatotherinstancevariablesmightbeneeded.Oncewe
have identifiedtherelevantvariables,wecanwritea constructorthatinitializesthesevalues.
Let’s startwiththeactivatemethod.We cansignalthatthebuttonis active bymakingtheoutline
thickerandmakingthelabeltextblack.Hereis thecode(remembertheselfparameterreferstothebutton
object):
def activate(self):
"Sets thisbutton to ’active’."
self.label.setFill(’black’)
self.rect.setWidth(2)
self.active= 1