Python Programming: An Introduction to Computer Science

(Nora) #1
5.6.INTERACTIVEGRAPHICS 75

raw_input("Press<Enter> to quit.")

main()


Noticehowthecomplex calculationshave beeneliminated.Thisversionalsomakesit easytochangethe
sizeoftheGraphWin. Changingthewindow sizeto 640 x 480producesa larger, butcorrectlydrawnbar
graph. Intheoriginalprogram,allofthecalculationswouldhave toberedonetoaccommodatethenew
scalingfactorsinthelargerwindow.
Obviously, thesecondversionofourprogramis mucheasiertodevelopandunderstand.Whenyouare
doinggraphicsprogramming,give someconsiderationtochoosinga coordinatesystemthatwillmake your
taskassimpleaspossible.


5.6 Interactive Graphics.


Graphicalinterfacescanbeusedforinputaswellasoutput.Ina GUIenvironment,userstypicallyinteract
withtheirapplicationsbyclickingonbuttons,choosingitemsfrommenus,andtypinginformationinto
on-screentextboxes.Theseapplicationsusea techniquecalledevent-drivenprogramming.Basically, the
programdrawsa setofinterfaceelements(oftencalledwidgets) onthescreen,andthenwaitsfortheuserto
dosomething.
Whentheusermovesthemouse,clicksa buttonortypesa key onthekeyboard,thisgeneratesanevent.
Basically, aneventis anobjectthatencapsulatesdataaboutwhatjusthappened.Theeventobjectis thensent
off toanappropriatepartoftheprogramtobeprocessed.Forexample,a clickona buttonmightproduce
abuttonevent. Thiseventwouldbepassedtothebuttonhandlingcode,whichwouldthenperformthe
appropriateactioncorrespondingtothatbutton.
Event-drivenprogrammingcanbetricky fornoviceprogrammers,sinceit’s hardtofigureout“who’s in
charge”at any givenmoment.Thegraphicsmodulehidestheunderlyingevent-handlingmechanismsand
providestwo simplewaysofgettinguserinputinaGraphWin.


5.6.1 GettingMouseClicks


We cangetgraphicalinformationfromtheuserviathegetMousemethodoftheGraphWinclass.When
getMouseisinvokedonaGraphWin, theprogrampausesandwaitsfortheusertoclickthemouse
somewhereinthegraphicswindow. Thespotwheretheuserclicksis returnedtotheprogramasaPoint.
Hereis a bitofcodethatreportsthecoordinatesoftensuccessive mouseclicks.


from graphics import*


win = GraphWin("ClickMe!")
for i in range(10):
p = win.getMouse()
print "You clicked(%d, %d)" % (p.getX(), p.getY())


ThevaluereturnedbygetMouse()isa ready-madePoint. We canuseit like any otherpointusing
accessorssuchasgetXandgetYorothermethodssuchasdrawandmove.
Hereis anexampleofaninteractive programthatallowstheusertodraw a trianglebyclickingonthree
pointsina graphicswindow. Thisexampleis completelygraphical,makinguseofTextobjectsasprompts.
Nointeractionwitha Pythontextwindow is required.If youareprogrammingina Windowsenvironment,
youcannamethisprogramusinga.pywextension.Thenwhentheprogramis run,it willnotevendisplay
thePythonshellwindow.


Program: triangle.pyw


from graphics import*


def main():
win = GraphWin("Drawa Triangle")

Free download pdf