Python Programming: An Introduction to Computer Science

(Nora) #1
64 CHAPTER5. OBJECTSANDGRAPHICS

Figure5.2:Graphicswindow withtwo pointsdrawn.

polygonsandtext.Eachoftheseobjectsis createdanddrawnin a similarfashion.Hereis a sampleinteraction
todraw variousshapesintoaGraphWin.





Open a graphicswindow


win = GraphWin(’Shapes’)


Draw a red circlecentered at point (100,100) with radius 30


center = Point(100,100)
circ = Circle(center,30)
circ.setFill(’red’)
circ.draw(win)


Put a textuallabel in the center of the circle


label = Text(center,"Red Circle")
label.draw(win)


Draw a squareusing a Rectangle object


rect = Rectangle(Point(30,30), Point(70,70))
rect.draw(win)


Draw a linesegment using a Line object


line = Line(Point(20,30),Point(180, 165))
line.draw(win)


Draw an ovalusing the Oval object


oval = Oval(Point(20,150),Point(180,199))
oval.draw(win)





Trytofigureoutwhateachofthesestatementsdoes.If youtypetheminasshown,thefinalresultwilllook
like Figure5.3.


5.3 UsingGraphicalObjects


Someoftheexamplesintheabove interactionsmaylooka bitstrangetoyou. To reallyunderstandthe
graphicsmodule,weneedtotake anobject-orientedpointofview. Recall,objectscombinedatawith
operations.Computationis performedbyaskinganobjectto carryoutoneofitsoperations.Inordertomake
useofobjects,youneedtoknow how tocreatethemandhow torequestoperations.
Intheinteractive examplesabove, wemanipulatedseveraldifferentkindsofobjects:GraphWin,Point,
Circle,Oval,Line,Text, andRectangle. Theseareexamplesofclasses. Everyobjectis aninstance
ofsomeclass,andtheclassdescribesthepropertiestheinstancewillhave.
Borrowinga biologicalmetaphor, whenwesaythatFidois a dog,weareactuallysayingthatFidois a
specificindividualinthelargerclassofalldogs. InOOterminology, Fidois aninstanceofthedogclass.

Free download pdf