Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967. Show
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an >>> turtle.setheading(90) >>> turtle.heading() 90.09, give it the command >>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.00, and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command >>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.01, and it rotates in-place 25 degrees clockwise. Turtle star Turtle can draw intricate shapes using programs that repeat simple moves. from turtle import * color('red', 'yellow') begin_fill() while True: forward(200) left(170) if abs(pos()) < 1: break end_fill() done() By combining together these and similar commands, intricate shapes and pictures can easily be drawn. The module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5. It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the >>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.03 switch. The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses for the underlying graphics, it needs a version of Python installed with Tk support. The object-oriented interface uses essentially two+two classes:
The procedural interface provides functions which are derived from the methods of the classes and . They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called. To use multiple turtles on a screen one has to use the object-oriented interface. Note In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here. Overview of available Turtle and Screen methodsTurtle methodsTurtle motionMove and draw| | | | | | | | Tell Turtle’s state| Setting and measurementPen controlDrawing state| | | | | Color controlFillingMore drawing controlTurtle stateVisibility| | Appearance| Using eventsSpecial Turtle methods| Methods of TurtleScreen/ScreenWindow controlAnimation controlUsing screen events| | | Settings and special methods| Input methodsMethods specific to ScreenMethods of RawTurtle/Turtle and corresponding functionsMost of the examples in this section refer to a Turtle instance called >>> turtle.setheading(90) >>> turtle.heading() 90.08. Turtle motionturtle.forward(distance)turtle.fd(distance)Parametersdistance – a number (integer or float) Move the turtle forward by the specified distance, in the direction the turtle is headed. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)turtle.back(distance)turtle.bk(distance)turtle.backward(distance)Parameters distance – a number Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not change the turtle’s heading. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)turtle.right(angle)turtle.rt(angle)Parameters angle – a number (integer or float) Turn turtle right by angle units. (Units are by default degrees, but can be set via the and functions.) Angle orientation depends on the turtle mode, see . >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0 angle – a number (integer or float) Turn turtle left by angle units. (Units are by default degrees, but can be set via the and functions.) Angle orientation depends on the turtle mode, see . >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.0turtle.goto(x, y=None)turtle.setpos(x, y=None)turtle.setposition(x, y=None)Parameters
If y is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, x must be a pair of coordinates or a (e.g. as returned by ). Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)turtle.setx(x)Parameters x – a number (integer or float) Set the turtle’s first coordinate to x, leave second coordinate unchanged. >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)turtle.sety(y)Parameters y – a number (integer or float) Set the turtle’s second coordinate to y, leave first coordinate unchanged. >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)turtle.setheading(to_angle)turtle.seth(to_angle)Parameters to_angle – a number (integer or float) Set the orientation of the turtle to to_angle. Here are some common directions in degrees: standard mode logo mode 0 - east 0 - north 90 - north 90 - east 180 - west 180 - south 270 - south 270 - west >>> turtle.setheading(90) >>> turtle.heading() 90.0turtle.home() Move turtle to the origin – coordinates (0,0) – and set its heading to its start-orientation (which depends on the mode, see ). >>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0turtle.circle(radius, extent=None, steps=None)Parameters
Draw a circle with given radius. The center is radius units left of the turtle; extent – an angle – determines which part of the circle is drawn. If extent is not given, draw the entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position. Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction. Finally the direction of the turtle is changed by the amount of extent. As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. If not given, it will be calculated automatically. May be used to draw regular polygons. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)0turtle.dot(size=None, *color)Parameters
Draw a circular dot with diameter size, using color. If size is not given, the maximum of pensize+4 and 2*pensize is used. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)1turtle.stamp() Stamp a copy of the turtle shape onto the canvas at the current turtle position. Return a stamp_id for that stamp, which can be used to delete it by calling >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)36. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)2turtle.clearstamp(stampid)Parameters stampid – an integer, must be return value of previous call Delete stamp with given stampid. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)3turtle.clearstamps(n=None)Parameters n – an integer (or >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29) Delete all or first/last n of turtle’s stamps. If n is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, delete all stamps, if n > 0 delete first n stamps, else if n < 0 delete last n stamps. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)4turtle.undo() Undo (repeatedly) the last turtle action(s). Number of available undo actions is determined by the size of the undobuffer. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)5turtle.speed(speed=None)Parameters speed – an integer in the range 0..10 or a speedstring (see below) Set the turtle’s speed to an integer value in the range 0..10. If no argument is given, return current speed. If input is a number greater than 10 or smaller than 0.5, speed is set to 0. Speedstrings are mapped to speedvalues as follows:
Speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning. Attention: speed = 0 means that no animation takes place. forward/back makes turtle jump and likewise left/right make the turtle turn instantly. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)6 Tell Turtle’s stateturtle.position()turtle.pos()Return the turtle’s current location (x,y) (as a vector). >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)7turtle.towards(x, y=None)Parameters
Return the angle between the line from turtle position to position specified by (x,y), the vector or the other turtle. This depends on the turtle’s start orientation which depends on the mode - “standard”/”world” or “logo”. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)8turtle.xcor() Return the turtle’s x coordinate. >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)9turtle.ycor() Return the turtle’s y coordinate. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)0turtle.heading() Return the turtle’s current heading (value depends on the turtle mode, see ). >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)1turtle.distance(x, y=None)Parameters
Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)2 Settings for measurementturtle.degrees(fullcircle=360.0)Parametersfullcircle – a number Set angle measurement units, i.e. set number of “degrees” for a full circle. Default value is 360 degrees. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)3turtle.radians() Set the angle measurement units to radians. Equivalent to >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)44. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)4 Pen controlDrawing stateturtle.pendown()turtle.pd()turtle.down()Pull the pen down – drawing when moving. turtle.penup()turtle.pu()turtle.up()Pull the pen up – no drawing when moving. turtle.pensize(width=None)turtle.width(width=None)Parameterswidth – a positive number Set the line thickness to width or return it. If resizemode is set to “auto” and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, the current pensize is returned. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)5turtle.pen(pen=None, **pendict)Parameters
Return or set the pen’s attributes in a “pen-dictionary” with the following key/value pairs:
This dictionary can be used as argument for a subsequent call to to restore the former pen-state. Moreover one or more of these attributes can be provided as keyword-arguments. This can be used to set several pen attributes in one statement. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)6turtle.isdown() Return >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)46 if pen is down, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)47 if it’s up. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)7 Color controlturtle.pencolor(*args)Return or set the pencolor. Four input formats are allowed: >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)54 Return the current pencolor as color specification string or as a tuple (see example). May be used as input to another color/pencolor/fillcolor call. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)49 Set pencolor to colorstring, which is a Tk color specification string, such as >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)50, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)51, or >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)52. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)53 Set pencolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see ). >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)55 Set pencolor to the RGB color represented by r, g, and b. Each of r, g, and b must be in the range 0..colormode. If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)8turtle.fillcolor(*args) Return or set the fillcolor. Four input formats are allowed: >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)55 Return the current fillcolor as color specification string, possibly in tuple format (see example). May be used as input to another color/pencolor/fillcolor call. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)57 Set fillcolor to colorstring, which is a Tk color specification string, such as >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)50, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)51, or >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)52. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)61 Set fillcolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see ). >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)63 Set fillcolor to the RGB color represented by r, g, and b. Each of r, g, and b must be in the range 0..colormode. If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)9turtle.color(*args) Return or set pencolor and fillcolor. Several input formats are allowed. They use 0 to 3 arguments as follows: >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)53 Return the current pencolor and the current fillcolor as a pair of color specification strings or tuples as returned by and . >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)67, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)68, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)69 Inputs as in , set both, fillcolor and pencolor, to the given value. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)71, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)72 Equivalent to >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)73 and >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)74 and analogously if the other input format is used. If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.00 See also: Screen method . Fillingturtle.filling()Return fillstate ( >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)46 if filling, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)47 else). >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.01turtle.begin_fill() To be called just before drawing a shape to be filled. turtle.end_fill()Fill the shape drawn after the last call to . Whether or not overlap regions for self-intersecting polygons or multiple shapes are filled depends on the operating system graphics, type of overlap, and number of overlaps. For example, the Turtle star above may be either all yellow or have some white regions. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.02 More drawing controlturtle.reset()Delete the turtle’s drawings from the screen, re-center the turtle and set variables to the default values. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.03turtle.clear() Delete the turtle’s drawings from the screen. Do not move turtle. State and position of the turtle as well as drawings of other turtles are not affected. turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))Parameters
Write text - the string representation of arg - at the current turtle position according to align (“left”, “center” or “right”) and with the given font. If move is true, the pen is moved to the bottom-right corner of the text. By default, move is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)47. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.04 Turtle stateVisibilityturtle.hideturtle()turtle.ht()Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing, because hiding the turtle speeds up the drawing observably. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.05turtle.showturtle()turtle.st() Make the turtle visible. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.06turtle.isvisible() Return >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)46 if the Turtle is shown, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)47 if it’s hidden. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.07 Appearanceturtle.shape(name=None)Parametersname – a string which is a valid shapename Set turtle shape to shape with given name or, if name is not given, return name of current shape. Shape with name must exist in the TurtleScreen’s shape dictionary. Initially there are the following polygon shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”. To learn about how to deal with shapes see Screen method . >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.08turtle.resizemode(rmode=None)Parameters rmode – one of the strings “auto”, “user”, “noresize” Set resizemode to one of the values: “auto”, “user”, “noresize”. If rmode is not given, return current resizemode. Different resizemodes have the following effects:
>>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)84 is called by when used with arguments. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.09turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None)turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)Parameters
Return or set the pen’s attributes x/y-stretchfactors and/or outline. Set resizemode to “user”. If and only if resizemode is set to “user”, the turtle will be displayed stretched according to its stretchfactors: stretch_wid is stretchfactor perpendicular to its orientation, stretch_len is stretchfactor in direction of its orientation, outline determines the width of the shapes’s outline. >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.00turtle.shearfactor(shear=None)Parameters shear – number (optional) Set or return the current shearfactor. Shear the turtleshape according to the given shearfactor shear, which is the tangent of the shear angle. Do not change the turtle’s heading (direction of movement). If shear is not given: return the current shearfactor, i. e. the tangent of the shear angle, by which lines parallel to the heading of the turtle are sheared. >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.01turtle.tilt(angle)Parameters angle – a number Rotate the turtleshape by angle from its current tilt-angle, but do not change the turtle’s heading (direction of movement). >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.02turtle.settiltangle(angle)Parameters angle – a number Rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. Do not change the turtle’s heading (direction of movement). >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.03 Deprecated since version 3.1. turtle.tiltangle(angle=None)Parametersangle – a number (optional) Set or return the current tilt-angle. If angle is given, rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. Do not change the turtle’s heading (direction of movement). If angle is not given: return the current tilt-angle, i. e. the angle between the orientation of the turtleshape and the heading of the turtle (its direction of movement). >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.04turtle.shapetransform(t11=None, t12=None, t21=None, t22=None)Parameters
Set or return the current transformation matrix of the turtle shape. If none of the matrix elements are given, return the transformation matrix as a tuple of 4 elements. Otherwise set the given elements and transform the turtleshape according to the matrix consisting of first row t11, t12 and second row t21, t22. The determinant t11 * t22 - t12 * t21 must not be zero, otherwise an error is raised. Modify stretchfactor, shearfactor and tiltangle according to the given matrix. >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.05turtle.get_shapepoly() Return the current shape polygon as tuple of coordinate pairs. This can be used to define a new shape or components of a compound shape. >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.06 Using eventsturtle.onclick(fun, btn=1, add=None)Parameters
Bind fun to mouse-click events on this turtle. If fun is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, existing bindings are removed. Example for the anonymous turtle, i.e. the procedural way: >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.07turtle.onrelease(fun, btn=1, add=None)Parameters
Bind fun to mouse-button-release events on this turtle. If fun is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, existing bindings are removed. >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.08turtle.ondrag(fun, btn=1, add=None)Parameters
Bind fun to mouse-move events on this turtle. If fun is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, existing bindings are removed. Remark: Every sequence of mouse-move-events on a turtle is preceded by a mouse-click event on that turtle. >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.09 Subsequently, clicking and dragging the Turtle will move it across the screen thereby producing handdrawings (if pen is down). Special Turtle methodsturtle.begin_poly()Start recording the vertices of a polygon. Current turtle position is first vertex of polygon. turtle.end_poly()Stop recording the vertices of a polygon. Current turtle position is last vertex of polygon. This will be connected with the first vertex. turtle.get_poly()Return the last recorded polygon. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)0turtle.clone() Create and return a clone of the turtle with same position, heading and turtle properties. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)1turtle.getturtle()turtle.getpen() Return the Turtle object itself. Only reasonable use: as a function to return the “anonymous turtle”: >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)2turtle.getscreen() Return the object the turtle is drawing on. TurtleScreen methods can then be called for that object. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)3turtle.setundobuffer(size)Parameters size – an integer or >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29 Set or disable undobuffer. If size is an integer, an empty undobuffer of given size is installed. size gives the maximum number of turtle actions that can be undone by the method/function. If size is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, the undobuffer is disabled. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)4turtle.undobufferentries() Return number of entries in the undobuffer. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)5 Compound shapesTo use compound turtle shapes, which consist of several polygons of different color, you must use the helper class explicitly as described below:
Note The class is used internally by the method in different ways. The application programmer has to deal with the Shape class only when using compound shapes like shown above! Methods of TurtleScreen/Screen and corresponding functionsMost of the examples in this section refer to a TurtleScreen instance called >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.006. Window controlturtle.bgcolor(*args)Parametersargs – a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers Set or return background color of the TurtleScreen. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)8turtle.bgpic(picname=None)Parameters picname – a string, name of a gif-file or >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.007, or >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29 Set background image or return name of current backgroundimage. If picname is a filename, set the corresponding image as background. If picname is >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.007, delete background image, if present. If picname is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, return the filename of the current backgroundimage. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)9turtle.clear() Note This TurtleScreen method is available as a global function only under the name >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.011. The global function >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.012 is a different one derived from the Turtle method >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.012.turtle.clearscreen() Delete all drawings and all turtles from the TurtleScreen. Reset the now empty TurtleScreen to its initial state: white background, no background image, no event bindings and tracing on. turtle.reset()Note This TurtleScreen method is available as a global function only under the name >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.014. The global function >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.015 is another one derived from the Turtle method >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.015.turtle.resetscreen() Reset all Turtles on the Screen to their initial state. turtle.screensize(canvwidth=None, canvheight=None, bg=None)Parameters
If no arguments are given, return current (canvaswidth, canvasheight). Else resize the canvas the turtles are drawing on. Do not alter the drawing window. To observe hidden parts of the canvas, use the scrollbars. With this method, one can make visible those parts of a drawing which were outside the canvas before. >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)0 e.g. to search for an erroneously escaped turtle ;-) turtle.setworldcoordinates(llx, lly, urx, ury)Parameters
Set up user-defined coordinate system and switch to mode “world” if necessary. This performs a >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.017. If mode “world” is already active, all drawings are redrawn according to the new coordinates. ATTENTION: in user-defined coordinate systems angles may appear distorted. >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)1 Animation controlturtle.delay(delay=None)Parametersdelay – positive integer Set or return the drawing delay in milliseconds. (This is approximately the time interval between two consecutive canvas updates.) The longer the drawing delay, the slower the animation. Optional argument: >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)2turtle.tracer(n=None, delay=None)Parameters
Turn turtle animation on/off and set delay for update drawings. If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) When called without arguments, returns the currently stored value of n. Second argument sets delay value (see ). >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)3turtle.update() Perform a TurtleScreen update. To be used when tracer is turned off. See also the RawTurtle/Turtle method . Using screen eventsturtle.listen(xdummy=None, ydummy=None)Set focus on TurtleScreen (in order to collect key-events). Dummy arguments are provided in order to be able to pass to the onclick method. turtle.onkey(fun, key)turtle.onkeyrelease(fun, key)Parameters
Bind fun to key-release event of key. If fun is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, event bindings are removed. Remark: in order to be able to register key-events, TurtleScreen must have the focus. (See method .) >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)4turtle.onkeypress(fun, key=None)Parameters
Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Remark: in order to be able to register key-events, TurtleScreen must have focus. (See method .) >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)5turtle.onclick(fun, btn=1, add=None)turtle.onscreenclick(fun, btn=1, add=None)Parameters
Bind fun to mouse-click events on this screen. If fun is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29, existing bindings are removed. Example for a TurtleScreen instance named >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.006 and a Turtle instance named >>> turtle.setheading(90) >>> turtle.heading() 90.08: >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)6 Note This TurtleScreen method is available as a global function only under the name >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.032. The global function >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.033 is another one derived from the Turtle method >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.033.turtle.ontimer(fun, t=0)Parameters
Install a timer that calls fun after t milliseconds. >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)7turtle.mainloop()turtle.done() Starts event loop - calling Tkinter’s mainloop function. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics. >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)8 Input methodsturtle.textinput(title, prompt)Parameters
Pop up a dialog window for input of a string. Parameter title is the title of the dialog window, prompt is a text mostly describing what information to input. Return the string input. If the dialog is canceled, return >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29. >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)9turtle.numinput(title, prompt, default=None, minval=None, maxval=None)Parameters
Pop up a dialog window for input of a number. title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. default: default value, minval: minimum value for input, maxval: maximum value for input. The number input must be in the range minval .. maxval if these are given. If not, a hint is issued and the dialog remains open for correction. Return the number input. If the dialog is canceled, return >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29. >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)0 Settings and special methodsturtle.mode(mode=None)Parametersmode – one of the strings “standard”, “logo” or “world” Set turtle mode (“standard”, “logo” or “world”) and perform reset. If mode is not given, current mode is returned. Mode “standard” is compatible with old . Mode “logo” is compatible with most Logo turtle graphics. Mode “world” uses user-defined “world coordinates”. Attention: in this mode angles appear distorted if >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.038 unit-ratio doesn’t equal 1. Mode Initial turtle heading positive angles “standard” to the right (east) counterclockwise “logo” upward (north) clockwise >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)1turtle.colormode(cmode=None)Parameters cmode – one of the values 1.0 or 255 Return the colormode or set it to 1.0 or 255. Subsequently r, g, b values of color triples have to be in the range 0..*cmode*. >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)2turtle.getcanvas() Return the Canvas of this TurtleScreen. Useful for insiders who know what to do with a Tkinter Canvas. >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)3turtle.getshapes() Return a list of names of all currently available turtle shapes. >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)4turtle.register_shape(name, shape=None)turtle.addshape(name, shape=None) There are three different ways to call this function:
Add a turtle shape to TurtleScreen’s shapelist. Only thusly registered shapes can be used by issuing the command >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.041.turtle.turtles() Return the list of turtles on the screen. >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)7turtle.window_height() Return the height of the turtle window. >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)8turtle.window_width() Return the width of the turtle window. >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)9 Methods specific to Screen, not inherited from TurtleScreenturtle.bye()Shut the turtlegraphics window. turtle.exitonclick()Bind >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)18 method to mouse clicks on the Screen. If the value “using_IDLE” in the configuration dictionary is >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)47 (default value), also enter mainloop. Remark: If IDLE with the >>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.03 switch (no subprocess) is used, this value should be set to >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)46 in >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.046. In this case IDLE’s own mainloop is active also for the client script.turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom']) Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.046 file.Parameters
>>> turtle.setheading(90) >>> turtle.heading() 90.00turtle.title(titlestring)Parameters titlestring – a string that is shown in the titlebar of the turtle graphics window Set title of turtle window to titlestring. >>> turtle.setheading(90) >>> turtle.heading() 90.01 Public classesclass turtle.RawTurtle(canvas)class turtle.RawPen(canvas)Parameterscanvas – a >>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.06, a or a Create a turtle. The turtle has all methods described above as “methods of Turtle/RawTurtle”. class turtle.TurtleSubclass of RawTurtle, has the same interface but draws on a default object created automatically when needed for the first time. class turtle.TurtleScreen(cv)Parameterscv – a >>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.06 Provides screen oriented methods like >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.055 etc. that are described above.class turtle.Screen Subclass of TurtleScreen, with . class turtle.ScrolledCanvas(master)Parametersmaster – some Tkinter widget to contain the ScrolledCanvas, i.e. a Tkinter-canvas with scrollbars added Used by class Screen, which thus automatically provides a ScrolledCanvas as playground for the turtles. class turtle.Shape(type_, data)Parameterstype_ – one of the strings “polygon”, “image”, “compound” Data structure modeling shapes. The pair >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.056 must follow this specification: type_ data “polygon” a polygon-tuple, i.e. a tuple of pairs of coordinates “image” an image (in this form only used internally!) “compound” >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)29 (a compound shape has to be constructed using the method)addcomponent(poly, fill, outline=None)Parameters
Example: >>> turtle.setheading(90) >>> turtle.heading() 90.02 See . class turtle.Vec2D(x, y)A two-dimensional vector class, used as a helper class for implementing turtle graphics. May be useful for turtle graphics programs too. Derived from tuple, so a vector is a tuple! Provides (for a, b vectors, k number):
Help and configurationHow to use helpThe public methods of the Screen and Turtle classes are documented extensively via docstrings. So these can be used as online-help via the Python help facilities:
These modified docstrings are created automatically together with the function definitions that are derived from the methods at import time. Translation of docstrings into different languagesThere is a utility to create a dictionary the keys of which are the method names and the values of which are the docstrings of the public methods of the classes Screen and Turtle. turtle.write_docstringdict(filename='turtle_docstringdict')Parametersfilename – a string, used as filename Create and write docstring-dictionary to a Python script with the given filename. This function has to be called explicitly (it is not used by the turtle graphics classes). The docstring dictionary will be written to the Python script >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.067. It is intended to serve as a template for translation of the docstrings into different languages. If you (or your students) want to use with online help in your native language, you have to translate the docstrings and save the resulting file as e.g. >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.069. If you have an appropriate entry in your >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.046 file this dictionary will be read in at import time and will replace the original English docstrings. At the time of this writing there are docstring dictionaries in German and in Italian. (Requests please to glingl@aon.at.) How to configure Screen and TurtlesThe built-in default configuration mimics the appearance and behaviour of the old turtle module in order to retain best possible compatibility with it. If you want to use a different configuration which better reflects the features of this module or which better fits to your needs, e.g. for use in a classroom, you can prepare a configuration file >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.046 which will be read at import time and modify the configuration according to its settings. The built in configuration would correspond to the following turtle.cfg: >>> turtle.setheading(90) >>> turtle.heading() 90.05 Short explanation of selected entries:
There can be a >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.046 file in the directory where is stored and an additional one in the current working directory. The latter will override the settings of the first one. The >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.085 directory contains a >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.046 file. You can study it as an example and see its effects when running the demos (preferably not from within the demo-viewer). — Demo scriptsThe package includes a set of demo scripts. These scripts can be run and viewed using the supplied demo viewer as follows: >>> turtle.setheading(90) >>> turtle.heading() 90.06 Alternatively, you can run the demo scripts individually. For example, >>> turtle.setheading(90) >>> turtle.heading() 90.07 The package directory contains:
The demo scripts are: Name Description Features bytedesign complex classical turtle graphics pattern >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)96, delay, >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)97 chaos graphs Verhulst dynamics, shows that computer’s computations can generate results sometimes against the common sense expectations world coordinates clock analog clock showing time of your computer turtles as clock’s hands, ontimer colormixer experiment with r, g, b >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)79 forest 3 breadth-first trees randomization fractalcurves Hilbert & Koch curves recursion lindenmayer ethnomathematics (indian kolams) L-System minimal_hanoi Towers of Hanoi Rectangular Turtles as Hanoi discs (shape, shapesize) nim play the classical nim game with three heaps of sticks against the computer. turtles as nimsticks, event driven (mouse, keyboard) paint super minimalistic drawing program >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)77 peace elementary turtle: appearance and animation penrose aperiodic tiling with kites and darts >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)29 planet_and_moon simulation of gravitational system compound shapes, >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)31 round_dance dancing turtles rotating pairwise in opposite direction compound shapes, clone shapesize, tilt, get_shapepoly, update sorting_animate visual demonstration of different sorting methods simple alignment, randomization tree a (graphical) breadth first tree (using generators) >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)83 two_canvases simple design turtles on two canvases wikipedia a pattern from the wikipedia article on turtle graphics >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)83, >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)32 yinyang another elementary example >>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)27 Have fun! Changes since Python 2.6
Changes since Python 3.0
|