Transcription of Chapter 13 Turtle Graphics - Washington State University
1 Chapter 13 Turtle IntroductionGraphical User Interfaces (GUI s) provide a rich environment in which information can be ex-changed between a user and the computer. GUI s are not limited to simply displaying text andreading text from the keyboard. GUI s enable users to control the behavior of a program by per-forming actions such as using the mouse to drag or click on graphical objects. GUI s can makeusing programs much more intuitive and easier to learn since they provide users with immediatevisual feedback that shows the effects of their are many Python packages that can be used to create Graphics and GUI s. Two graphicsmodules, called Turtle and tkinter, come as a part of Python s standard library. tkinter is primarilydesigned for creating GUI s. In fact, IDLE is built using tkinter. However, we will focus on theturtle module that is primarily used as a simple Graphics package but can also be used to createsimple GUI Turtle module is an implementation of Turtle Graphics and uses tkinter for the creationof the underlying Graphics .
2 Turtle Graphics dates back to the 1960 s and was part of the Logoprogramming Chapter provides an introduction to using the Graphics capabilitiesof the Turtle module and demonstrates the creation of simple images and simple GUI s for gamesand applications. We will not delve into the details of building and designing GUI s, but many ofthe skills developed here can be applied to more complicated GUI designs if you wish to pursuethat in the future. In addition to helping you gain practical programming skills, learning to useturtle Graphics is fun and it enables you to use Python to be visually creative! Turtle BasicsAmong other things, the methods in the Turtle module allow us to draw images. The idea behindthe Turtle part of Turtle Graphics is based on a metaphor. Imagine you have a Turtle on a canvasthat is holding a pen. The pen can be either up (not touching the canvas) or down (touching thecanvas). Now think of the Turtle as a robot that you can control by issuing commands.
3 When theFrom the 13. Turtle GRAPHICSpen it holds is down, the Turtle leaves a trail when you tell it to move to a new location. When thepen is up, the Turtle moves to a new position but no trail is left. In addition to position, the turtlealso has a heading, , a direction, of forward movement. The Turtle module provides commandsthat can set the Turtle s position and heading, control its forward and backward movement, specifythe type of pen it is holding, etc. By controlling the movement and orientation of the Turtle as wellas the pen it is holding, you can create drawings from the trails the Turtle Importing Turtle GraphicsIn order to start using Turtle Graphics , we need to import the Turtle module. Start Python/IDLE andtype the following:Listing the Turtle module.>>>importturtleastThis imports theturtlemodule using the identifiert. By importing the module this way weaccess the methods within the module usingt.<object>instead ofturtle.
4 <object>. Toensure that the module was properly imported, use thedir()function as shown in Listing ()to view theturtlemodule s methods and >>>dir(t)2[ Canvas , Pen , RawPen , RawTurtle , Screen , ScrolledCanvas ,3 Shape , TK , TNavigator , TPen , Tbuffer , Terminator ,4 Turtle , TurtleGraphicsError , TurtleScreen , TurtleScreenBase ,5 Vec2D , _CFG , _LANGUAGE , _Root , _Screen , _TurtleImage ,6 __all__ , __builtins__ , __cached__ , __doc__ , __file__ , <<MANY LINES OF OUTPUT DELETED>>8 window_width , write , write_docstringdict , xcor , ycor ]Thelistreturned by thedir()function in Listing has been truncated in all, thereare 173 items in thislist. To learn more about any of these attributes or methods, you can usethehelp()function. For example, to learn about theforward()method, enter the statementshown in line 1 of Listing about theforward()method usinghelp().1>>>help( )2 Help on function forward in module Turtle :34forward(distance)5 Move the Turtle forward by the specified Turtle BASICS3137 Aliases: forward | fd89 Argument:10distance -- a number (integer or float)1112 Move the Turtle forward by the specified distance, in the direction13the Turtle is <<REMAINING OUTPUT DELETED>>From this we learn, as shown in lines 12 and 13, that this method moves the Turtle forward bythe specified distance, in the direction the Turtle is headed.
5 We also learn that there is a shortername for this method:fd(). Your First DrawingLet s begin by telling our Turtle to draw a line. Try entering the command shown in Listing a line with a length of 100 units.>>> (100)As shown in Fig. , a Graphics window should appear in which you see a small arrow 100units to the right of the center of the thin black line is drawn from the center of thewindow to the tail of the arrow. The arrow represents our Turtle and the direction the arrow ispointing indicates the current heading. Thefd()method is a shorthand for theforward()method the two methods are ()takes one integer argument that specifies the num-ber of units you want to move the Turtle forward in the direction of the current youprovide a negative argument, the Turtle moves backwards the specified amount. Alternatively, tomove backward one can call eitherbackward(),back(), orbk().The default shape for our Turtle is an arrow but if we wanted to have it look like a Turtle wecould type the command shown in Listing the shape of the Turtle .
6 >>> (" Turtle ")This replaces the arrow with a small Turtle . We can change the shape of our Turtle to a numberof other built in shapes using theshape()method. We can also create custom shapes althoughwe won t cover that it first opens, this window may appear behind previously opened windows. So, you may have to search default the units correspond to pixels, , individual picture-elements or dots on your screen, but one can resetthe coordinates so that the units can correspond to whatever is most convenient to generate the desired 13. Turtle GRAPHICSF igure : A line of length 100 produced by thefd() though our Turtle s shape appears on the Graphics window, the Turtle is not truly part of ourdrawing. The shape of the Turtle is there to help you see the Turtle s current position and heading,but you need to issue other commands, such asfd(), to create a drawing. If you have created amasterpiece and you no longer want to see the Turtle in your Graphics window, you can enter thecommand shown in Listing to hide the Turtle s shape from the screen.
7 >>> ()This hides the image that currently represents the Turtle . In fact, you can continue to createlines even when the Turtle s shape is hidden, but you will not be able to see the Turtle s currentposition nor its heading. If you want to see the Turtle again, simply issue the command shown inListing the Turtle visible.>>> ()The Turtle s heading can be controlled using one of three methods:left(),right(), andsetheading(); or the shorter aliases oflt(),rt(), andseth(), ()andright()turn the Turtle either to the left or right, respectively, by the number of degrees given asthe argument. These turns are relative to the Turtle s current heading. So, for example,left(45)causes the Turtle to turn 45 degrees to the left. On the other hand,setheading()andseth() Turtle BASICS315 Figure : A square the absolute heading of the Turtle . A heading of 0 is horizontally to the right ( , east), 90 isup ( , north), 135 is up and to the left ( , northwest), and so you have previously entered the command of Listing , enter the commands inListing After doing this you should see a square drawn in the Graphics window as shown inFig.
8 To change the Turtle s heading and draw a square >>> (90)2>>> (100)3>>> (90)4>>> (100)5>>> (90)6>>> (100)What if we want to change the location of the Turtle without generating a line? We can ac-complish this by calling the methodpenup()before we enter commands to move the Turtle . Tore-enable drawing, we call the methodpendown().We can also move the Turtle to a specific position within the Graphics window by using thesetposition()method (or its aliasessetpos()andgoto()).setposition() s argu-ments are the desiredxandyvalues. The change of position does not affect the Turtle s the pen is down, when you callsetposition()(or its aliases), a straight line is drawn fromthat starting point to the position specified by the arguments. To demonstrate the use ofpenup(),pendown(), andsetposition(), issue the commands shown in Listing The resultingimage is shown in Fig. 13. Turtle GRAPHICSF igure : Result of moving the Turtle without drawing a line and then, once at the new location,drawing a ()andsetposition()to move the Turtle without making a >>> ()2>>> (100, -100)3>>> ()4>>> (130)If we want to erase everything that we previously drew, we can use either theclear()orreset() ()clears the drawing from the Graphics window but it leaves theturtle in its current position with its current ()clears the drawing and also returnsthe Turtle to its starting position in the center of the screen.
9 To illustrate the behavior ofclear(),enter the statement shown in Listing theclear()method to clear the image.>>> ()You should now see that the drawing that our Turtle generated has been cleared from the screenbut the Turtle is still in the State that you last specified. To demonstrate whatreset()does, enterthe command shown in Listing the Turtle and clearing the BASIC SHAPES AND USING ITERATION TO GENERATE GRAPHICS317>>> ()The Turtle is moved back to the center of the screen with its original heading. Note that we donot need to callclear()before we callreset().reset()will also clear the drawing inthe above example they were done sequentially solely for demonstrating their Basic Shapes and Using Iteration to Generate GraphicsThe commands shown in Listing that we used to draw a square box would be rather cum-bersome to type repeatedly if we wanted to draw more than one box. Observe that we are typingthe same commands four times.
10 As you already know, this sort of iteration can be accomplishedin a much simpler way using afor-loop. Let s create a function calledsquare()that drawsa square using afor-loop. The function takes one argument which is the length of the square ssides. Enter the commands in Listing that define this function and then call it three times,each time with a different length. The result should be the squares that are shown in Fig. function that draws a square using >>>defsquare(length) range(4) (length) (90) >>>square(60)7>>>square(100)8>>>square(2 00)Building a square from straight lines is relatively straightforward, but what if we want to drawcircles? Turtle provides a method calledcircle()that can be used to tell the Turtle to draw acomplete circle or only a part of a circle, , an arc. Thecircle()method has one mandatoryargument which is the radius of the circle. Optional arguments specify the extent, which is thedegrees of arc that are drawn, and the steps, which are the number of straight-line segments usedto approximate the circle.