1 ========================================
2 :mod:`turtle` --- Turtle graphics for Tk
3 ========================================
6 :synopsis: Turtle graphics for Tk
7 .. sectionauthor:: Gregor Lingl <gregor.lingl@aon.at>
12 Turtle graphics is a popular way for introducing programming to kids. It was
13 part of the original Logo programming language developed by Wally Feurzig and
14 Seymour Papert in 1966.
16 Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it the
17 command ``turtle.forward(15)``, and it moves (on-screen!) 15 pixels in the
18 direction it is facing, drawing a line as it moves. Give it the command
19 ``turtle.left(25)``, and it rotates in-place 25 degrees clockwise.
21 By combining together these and similar commands, intricate shapes and pictures
24 The :mod:`turtle` module is an extended reimplementation of the same-named
25 module from the Python standard distribution up to version Python 2.5.
27 It tries to keep the merits of the old turtle module and to be (nearly) 100%
28 compatible with it. This means in the first place to enable the learning
29 programmer to use all the commands, classes and methods interactively when using
30 the module from within IDLE run with the ``-n`` switch.
32 The turtle module provides turtle graphics primitives, in both object-oriented
33 and procedure-oriented ways. Because it uses :mod:`Tkinter` for the underlying
34 graphics, it needs a version of python installed with Tk support.
36 The object-oriented interface uses essentially two+two classes:
38 1. The :class:`TurtleScreen` class defines graphics windows as a playground for
39 the drawing turtles. Its constructor needs a :class:`Tkinter.Canvas` or a
40 :class:`ScrolledCanvas` as argument. It should be used when :mod:`turtle` is
41 used as part of some application.
43 The function :func:`Screen` returns a singleton object of a
44 :class:`TurtleScreen` subclass. This function should be used when
45 :mod:`turtle` is used as a standalone tool for doing graphics.
46 As a singleton object, inheriting from its class is not possible.
48 All methods of TurtleScreen/Screen also exist as functions, i.e. as part of
49 the procedure-oriented interface.
51 2. :class:`RawTurtle` (alias: :class:`RawPen`) defines Turtle objects which draw
52 on a :class:`TurtleScreen`. Its constructor needs a Canvas, ScrolledCanvas
53 or TurtleScreen as argument, so the RawTurtle objects know where to draw.
55 Derived from RawTurtle is the subclass :class:`Turtle` (alias: :class:`Pen`),
56 which draws on "the" :class:`Screen` - instance which is automatically
57 created, if not already present.
59 All methods of RawTurtle/Turtle also exist as functions, i.e. part of the
60 procedure-oriented interface.
62 The procedural interface provides functions which are derived from the methods
63 of the classes :class:`Screen` and :class:`Turtle`. They have the same names as
64 the corresponding methods. A screen object is automativally created whenever a
65 function derived from a Screen method is called. An (unnamed) turtle object is
66 automatically created whenever any of the functions derived from a Turtle method
69 To use multiple turtles an a screen one has to use the object-oriented interface.
72 In the following documentation the argument list for functions is given.
73 Methods, of course, have the additional first argument *self* which is
77 Overview over available Turtle and Screen methods
78 =================================================
85 | :func:`forward` | :func:`fd`
86 | :func:`backward` | :func:`bk` | :func:`back`
87 | :func:`right` | :func:`rt`
88 | :func:`left` | :func:`lt`
89 | :func:`goto` | :func:`setpos` | :func:`setposition`
92 | :func:`setheading` | :func:`seth`
103 | :func:`position` | :func:`pos`
110 Setting and measurement
116 | :func:`pendown` | :func:`pd` | :func:`down`
117 | :func:`penup` | :func:`pu` | :func:`up`
118 | :func:`pensize` | :func:`width`
139 | :func:`showturtle` | :func:`st`
140 | :func:`hideturtle` | :func:`ht`
146 | :func:`shapesize` | :func:`turtlesize`
147 | :func:`settiltangle`
156 Special Turtle methods
161 | :func:`getturtle` | :func:`getpen`
163 | :func:`setundobuffer`
164 | :func:`undobufferentries`
166 | :func:`window_width`
167 | :func:`window_height`
170 Methods of TurtleScreen/Screen
171 ------------------------------
176 | :func:`clear` | :func:`clearscreen`
177 | :func:`reset` | :func:`resetscreen`
179 | :func:`setworldcoordinates`
189 | :func:`onclick` | :func:`onscreenclick`
192 Settings and special methods
197 | :func:`register_shape` | :func:`addshape`
199 | :func:`window_height`
200 | :func:`window_width`
202 Methods specific to Screen
204 | :func:`exitonclick`
209 Methods of RawTurtle/Turtle and corresponding functions
210 =======================================================
212 Most of the examples in this section refer to a Turtle instance called
218 .. function:: forward(distance)
221 :param distance: a number (integer or float)
223 Move the turtle forward by the specified *distance*, in the direction the
226 >>> turtle.position()
228 >>> turtle.forward(25)
229 >>> turtle.position()
231 >>> turtle.forward(-75)
232 >>> turtle.position()
236 .. function:: back(distance)
240 :param distance: a number
242 Move the turtle backward by *distance*, opposite to the direction the
243 turtle is headed. Do not change the turtle's heading.
245 >>> turtle.position()
247 >>> turtle.backward(30)
248 >>> turtle.position()
252 .. function:: right(angle)
255 :param angle: a number (integer or float)
257 Turn turtle right by *angle* units. (Units are by default degrees, but
258 can be set via the :func:`degrees` and :func:`radians` functions.) Angle
259 orientation depends on the turtle mode, see :func:`mode`.
268 .. function:: left(angle)
271 :param angle: a number (integer or float)
273 Turn turtle left by *angle* units. (Units are by default degrees, but
274 can be set via the :func:`degrees` and :func:`radians` functions.) Angle
275 orientation depends on the turtle mode, see :func:`mode`.
283 .. function:: goto(x, y=None)
285 setposition(x, y=None)
287 :param x: a number or a pair/vector of numbers
288 :param y: a number or ``None``
290 If *y* is ``None``, *x* must be a pair of coordinates or a :class:`Vec2D`
291 (e.g. as returned by :func:`pos`).
293 Move turtle to an absolute position. If the pen is down, draw line. Do
294 not change the turtle's orientation.
296 >>> tp = turtle.pos()
299 >>> turtle.setpos(60,30)
302 >>> turtle.setpos((20,80))
305 >>> turtle.setpos(tp)
310 .. function:: setx(x)
312 :param x: a number (integer or float)
314 Set the turtle's first coordinate to *x*, leave second coordinate
317 >>> turtle.position()
320 >>> turtle.position()
324 .. function:: sety(y)
326 :param y: a number (integer or float)
328 Set the turtle's second coordinate to *y*, leave first coordinate unchanged.
330 >>> turtle.position()
333 >>> turtle.position()
337 .. function:: setheading(to_angle)
340 :param to_angle: a number (integer or float)
342 Set the orientation of the turtle to *to_angle*. Here are some common
343 directions in degrees:
345 =================== ====================
346 standard mode logo mode
347 =================== ====================
350 180 - west 180 - south
351 270 - south 270 - west
352 =================== ====================
354 >>> turtle.setheading(90)
361 Move turtle to the origin -- coordinates (0,0) -- and set its heading to
362 its start-orientation (which depends on the mode, see :func:`mode`).
365 .. function:: circle(radius, extent=None, steps=None)
367 :param radius: a number
368 :param extent: a number (or ``None``)
369 :param steps: an integer (or ``None``)
371 Draw a circle with given *radius*. The center is *radius* units left of
372 the turtle; *extent* -- an angle -- determines which part of the circle
373 is drawn. If *extent* is not given, draw the entire circle. If *extent*
374 is not a full circle, one endpoint of the arc is the current pen
375 position. Draw the arc in counterclockwise direction if *radius* is
376 positive, otherwise in clockwise direction. Finally the direction of the
377 turtle is changed by the amount of *extent*.
379 As the circle is approximated by an inscribed regular polygon, *steps*
380 determines the number of steps to use. If not given, it will be
381 calculated automatically. May be used to draw regular polygons.
383 >>> turtle.circle(50)
384 >>> turtle.circle(120, 180) # draw a semicircle
387 .. function:: dot(size=None, *color)
389 :param size: an integer >= 1 (if given)
390 :param color: a colorstring or a numeric color tuple
392 Draw a circular dot with diameter *size*, using *color*. If *size* is
393 not given, the maximum of pensize+4 and 2*pensize is used.
396 >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
399 .. function:: stamp()
401 Stamp a copy of the turtle shape onto the canvas at the current turtle
402 position. Return a stamp_id for that stamp, which can be used to delete
403 it by calling ``clearstamp(stamp_id)``.
405 >>> turtle.color("blue")
411 .. function:: clearstamp(stampid)
413 :param stampid: an integer, must be return value of previous
416 Delete stamp with given *stampid*.
418 >>> turtle.color("blue")
419 >>> astamp = turtle.stamp()
421 >>> turtle.clearstamp(astamp)
424 .. function:: clearstamps(n=None)
426 :param n: an integer (or ``None``)
428 Delete all or first/last *n* of turtle's stamps. If *n* is None, delete
429 all stamps, if *n* > 0 delete first *n* stamps, else if *n* < 0 delete
432 >>> for i in range(8):
433 ... turtle.stamp(); turtle.fd(30)
434 >>> turtle.clearstamps(2)
435 >>> turtle.clearstamps(-2)
436 >>> turtle.clearstamps()
441 Undo (repeatedly) the last turtle action(s). Number of available
442 undo actions is determined by the size of the undobuffer.
444 >>> for i in range(4):
445 ... turtle.fd(50); turtle.lt(80)
447 >>> for i in range(8):
451 .. function:: speed(speed=None)
453 :param speed: an integer in the range 0..10 or a speedstring (see below)
455 Set the turtle's speed to an integer value in the range 0..10. If no
456 argument is given, return current speed.
458 If input is a number greater than 10 or smaller than 0.5, speed is set
459 to 0. Speedstrings are mapped to speedvalues as follows:
467 Speeds from 1 to 10 enforce increasingly faster animation of line drawing
470 Attention: *speed* = 0 means that *no* animation takes
471 place. forward/back makes turtle jump and likewise left/right make the
472 turtle turn instantly.
480 .. function:: position()
483 Return the turtle's current location (x,y) (as a :class:`Vec2D` vector).
489 .. function:: towards(x, y=None)
491 :param x: a number or a pair/vector of numbers or a turtle instance
492 :param y: a number if *x* is a number, else ``None``
494 Return the angle between the line from turtle position to position specified
495 by (x,y), the vector or the other turtle. This depends on the turtle's start
496 orientation which depends on the mode - "standard"/"world" or "logo").
500 >>> turtle.towards(0,0)
506 Return the turtle's x coordinate.
510 >>> turtle.forward(100)
511 >>> print turtle.xcor()
517 Return the turtle's y coordinate.
521 >>> turtle.forward(100)
522 >>> print turtle.ycor()
526 .. function:: heading()
528 Return the turtle's current heading (value depends on the turtle mode, see
536 .. function:: distance(x, y=None)
538 :param x: a number or a pair/vector of numbers or a turtle instance
539 :param y: a number if *x* is a number, else ``None``
541 Return the distance from the turtle to (x,y), the given vector, or the given
542 other turtle, in turtle step units.
546 >>> turtle.distance(30,40)
550 >>> turtle.distance(joe)
554 Settings for measurement
555 ------------------------
557 .. function:: degrees(fullcircle=360.0)
559 :param fullcircle: a number
561 Set angle measurement units, i.e. set number of "degrees" for a full circle.
562 Default value is 360 degrees.
567 >>> turtle.degrees(400.0) # angle measurement in gon
572 .. function:: radians()
574 Set the angle measurement units to radians. Equivalent to
575 ``degrees(2*math.pi)``.
590 .. function:: pendown()
594 Pull the pen down -- drawing when moving.
597 .. function:: penup()
601 Pull the pen up -- no drawing when moving.
604 .. function:: pensize(width=None)
607 :param width: a positive number
609 Set the line thickness to *width* or return it. If resizemode is set to
610 "auto" and turtleshape is a polygon, that polygon is drawn with the same line
611 thickness. If no argument is given, the current pensize is returned.
615 >>> turtle.pensize(10) # from here on lines of width 10 are drawn
618 .. function:: pen(pen=None, **pendict)
620 :param pen: a dictionary with some or all of the below listed keys
621 :param pendict: one or more keyword-arguments with the below listed keys as keywords
623 Return or set the pen's attributes in a "pen-dictionary" with the following
626 * "shown": True/False
627 * "pendown": True/False
628 * "pencolor": color-string or color-tuple
629 * "fillcolor": color-string or color-tuple
630 * "pensize": positive number
631 * "speed": number in range 0..10
632 * "resizemode": "auto" or "user" or "noresize"
633 * "stretchfactor": (positive number, positive number)
634 * "outline": positive number
637 This dicionary can be used as argument for a subsequent call to :func:`pen`
638 to restore the former pen-state. Moreover one or more of these attributes
639 can be provided as keyword-arguments. This can be used to set several pen
640 attributes in one statement.
642 >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
644 {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
645 'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
646 'stretchfactor': (1,1), 'speed': 3}
647 >>> penstate=turtle.pen()
648 >>> turtle.color("yellow","")
651 {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
652 'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
653 'stretchfactor': (1,1), 'speed': 3}
654 >>> p.pen(penstate, fillcolor="green")
656 {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
657 'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
658 'stretchfactor': (1,1), 'speed': 3}
661 .. function:: isdown()
663 Return ``True`` if pen is down, ``False`` if it's up.
676 .. function:: pencolor(*args)
678 Return or set the pencolor.
680 Four input formats are allowed:
683 Return the current pencolor as color specification string, possibly in
684 hex-number format (see example). May be used as input to another
685 color/pencolor/fillcolor call.
687 ``pencolor(colorstring)``
688 Set pencolor to *colorstring*, which is a Tk color specification string,
689 such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
691 ``pencolor((r, g, b))``
692 Set pencolor to the RGB color represented by the tuple of *r*, *g*, and
693 *b*. Each of *r*, *g*, and *b* must be in the range 0..colormode, where
694 colormode is either 1.0 or 255 (see :func:`colormode`).
696 ``pencolor(r, g, b)``
697 Set pencolor to the RGB color represented by *r*, *g*, and *b*. Each of
698 *r*, *g*, and *b* must be in the range 0..colormode.
700 If turtleshape is a polygon, the outline of that polygon is drawn with the
703 >>> turtle.pencolor("brown")
704 >>> tup = (0.2, 0.8, 0.55)
705 >>> turtle.pencolor(tup)
706 >>> turtle.pencolor()
710 .. function:: fillcolor(*args)
712 Return or set the fillcolor.
714 Four input formats are allowed:
717 Return the current fillcolor as color specification string, possibly in
718 hex-number format (see example). May be used as input to another
719 color/pencolor/fillcolor call.
721 ``fillcolor(colorstring)``
722 Set fillcolor to *colorstring*, which is a Tk color specification string,
723 such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
725 ``fillcolor((r, g, b))``
726 Set fillcolor to the RGB color represented by the tuple of *r*, *g*, and
727 *b*. Each of *r*, *g*, and *b* must be in the range 0..colormode, where
728 colormode is either 1.0 or 255 (see :func:`colormode`).
730 ``fillcolor(r, g, b)``
731 Set fillcolor to the RGB color represented by *r*, *g*, and *b*. Each of
732 *r*, *g*, and *b* must be in the range 0..colormode.
734 If turtleshape is a polygon, the interior of that polygon is drawn
735 with the newly set fillcolor.
737 >>> turtle.fillcolor("violet")
738 >>> col = turtle.pencolor()
739 >>> turtle.fillcolor(col)
740 >>> turtle.fillcolor(0, .5, 0)
743 .. function:: color(*args)
745 Return or set pencolor and fillcolor.
747 Several input formats are allowed. They use 0 to 3 arguments as
751 Return the current pencolor and the current fillcolor as a pair of color
752 specification strings as returned by :func:`pencolor` and
755 ``color(colorstring)``, ``color((r,g,b))``, ``color(r,g,b)``
756 Inputs as in :func:`pencolor`, set both, fillcolor and pencolor, to the
759 ``color(colorstring1, colorstring2)``, ``color((r1,g1,b1), (r2,g2,b2))``
760 Equivalent to ``pencolor(colorstring1)`` and ``fillcolor(colorstring2)``
761 and analogously if the other input format is used.
763 If turtleshape is a polygon, outline and interior of that polygon is drawn
764 with the newly set colors.
766 >>> turtle.color("red", "green")
770 >>> color((40, 80, 120), (160, 200, 240))
772 ("#285078", "#a0c8f0")
775 See also: Screen method :func:`colormode`.
781 .. function:: fill(flag)
783 :param flag: True/False (or 1/0 respectively)
785 Call ``fill(True)`` before drawing the shape you want to fill, and
786 ``fill(False)`` when done. When used without argument: return fillstate
787 (``True`` if filling, ``False`` else).
789 >>> turtle.fill(True)
790 >>> for _ in range(3):
791 ... turtle.forward(100)
794 >>> turtle.fill(False)
797 .. function:: begin_fill()
799 Call just before drawing a shape to be filled. Equivalent to ``fill(True)``.
801 >>> turtle.color("black", "red")
802 >>> turtle.begin_fill()
803 >>> turtle.circle(60)
804 >>> turtle.end_fill()
807 .. function:: end_fill()
809 Fill the shape drawn after the last call to :func:`begin_fill`. Equivalent
816 .. function:: reset()
818 Delete the turtle's drawings from the screen, re-center the turtle and set
819 variables to the default values.
821 >>> turtle.position()
826 >>> turtle.position()
832 .. function:: clear()
834 Delete the turtle's drawings from the screen. Do not move turtle. State and
835 position of the turtle as well as drawings of other turtles are not affected.
838 .. function:: write(arg, move=False, align="left", font=("Arial", 8, "normal"))
840 :param arg: object to be written to the TurtleScreen
841 :param move: True/False
842 :param align: one of the strings "left", "center" or right"
843 :param font: a triple (fontname, fontsize, fonttype)
845 Write text - the string representation of *arg* - at the current turtle
846 position according to *align* ("left", "center" or right") and with the given
847 font. If *move* is True, the pen is moved to the bottom-right corner of the
848 text. By default, *move* is False.
850 >>> turtle.write("Home = ", True, align="center")
851 >>> turtle.write((0,0), True)
860 .. function:: showturtle()
863 Make the turtle visible.
865 >>> turtle.hideturtle()
866 >>> turtle.showturtle()
869 .. function:: hideturtle()
872 Make the turtle invisible. It's a good idea to do this while you're in the
873 middle of doing some complex drawing, because hiding the turtle speeds up the
876 >>> turtle.hideturtle()
879 .. function:: isvisible()
881 Return True if the Turtle is shown, False if it's hidden.
883 >>> turtle.hideturtle()
884 >>> print turtle.isvisible():
891 .. function:: shape(name=None)
893 :param name: a string which is a valid shapename
895 Set turtle shape to shape with given *name* or, if name is not given, return
896 name of current shape. Shape with *name* must exist in the TurtleScreen's
897 shape dictionary. Initially there are the following polygon shapes: "arrow",
898 "turtle", "circle", "square", "triangle", "classic". To learn about how to
899 deal with shapes see Screen method :func:`register_shape`.
903 >>> turtle.shape("turtle")
908 .. function:: resizemode(rmode=None)
910 :param rmode: one of the strings "auto", "user", "noresize"
912 Set resizemode to one of the values: "auto", "user", "noresize". If *rmode*
913 is not given, return current resizemode. Different resizemodes have the
916 - "auto": adapts the appearance of the turtle corresponding to the value of pensize.
917 - "user": adapts the appearance of the turtle according to the values of
918 stretchfactor and outlinewidth (outline), which are set by
920 - "noresize": no adaption of the turtle's appearance takes place.
922 resizemode("user") is called by :func:`shapesize` when used with arguments.
924 >>> turtle.resizemode("noresize")
925 >>> turtle.resizemode()
929 .. function:: shapesize(stretch_wid=None, stretch_len=None, outline=None)
931 :param stretch_wid: positive number
932 :param stretch_len: positive number
933 :param outline: positive number
935 Return or set the pen's attributes x/y-stretchfactors and/or outline. Set
936 resizemode to "user". If and only if resizemode is set to "user", the turtle
937 will be displayed stretched according to its stretchfactors: *stretch_wid* is
938 stretchfactor perpendicular to its orientation, *stretch_len* is
939 stretchfactor in direction of its orientation, *outline* determines the width
940 of the shapes's outline.
942 >>> turtle.resizemode("user")
943 >>> turtle.shapesize(5, 5, 12)
944 >>> turtle.shapesize(outline=8)
947 .. function:: tilt(angle)
949 :param angle: a number
951 Rotate the turtleshape by *angle* from its current tilt-angle, but do *not*
952 change the turtle's heading (direction of movement).
954 >>> turtle.shape("circle")
955 >>> turtle.shapesize(5,2)
962 .. function:: settiltangle(angle)
964 :param angle: a number
966 Rotate the turtleshape to point in the direction specified by *angle*,
967 regardless of its current tilt-angle. *Do not* change the turtle's heading
968 (direction of movement).
970 >>> turtle.shape("circle")
971 >>> turtle.shapesize(5,2)
972 >>> turtle.settiltangle(45)
975 >>> turtle.settiltangle(-45)
980 .. function:: tiltangle()
982 Return the current tilt-angle, i.e. the angle between the orientation of the
983 turtleshape and the heading of the turtle (its direction of movement).
985 >>> turtle.shape("circle")
986 >>> turtle.shapesize(5,2)
988 >>> turtle.tiltangle()
995 .. function:: onclick(fun, btn=1, add=None)
997 :param fun: a function with two arguments which will be called with the
998 coordinates of the clicked point on the canvas
999 :param num: number of the mouse-button, defaults to 1 (left mouse button)
1000 :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1001 added, otherwise it will replace a former binding
1003 Bind *fun* to mouse-click events on this turtle. If *fun* is ``None``,
1004 existing bindings are removed. Example for the anonymous turtle, i.e. the
1010 >>> onclick(turn) # Now clicking into the turtle will turn it.
1011 >>> onclick(None) # event-binding will be removed
1014 .. function:: onrelease(fun, btn=1, add=None)
1016 :param fun: a function with two arguments which will be called with the
1017 coordinates of the clicked point on the canvas
1018 :param num: number of the mouse-button, defaults to 1 (left mouse button)
1019 :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1020 added, otherwise it will replace a former binding
1022 Bind *fun* to mouse-button-release events on this turtle. If *fun* is
1023 ``None``, existing bindings are removed.
1025 >>> class MyTurtle(Turtle):
1026 ... def glow(self,x,y):
1027 ... self.fillcolor("red")
1028 ... def unglow(self,x,y):
1029 ... self.fillcolor("")
1031 >>> turtle = MyTurtle()
1032 >>> turtle.onclick(turtle.glow) # clicking on turtle turns fillcolor red,
1033 >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
1036 .. function:: ondrag(fun, btn=1, add=None)
1038 :param fun: a function with two arguments which will be called with the
1039 coordinates of the clicked point on the canvas
1040 :param num: number of the mouse-button, defaults to 1 (left mouse button)
1041 :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1042 added, otherwise it will replace a former binding
1044 Bind *fun* to mouse-move events on this turtle. If *fun* is ``None``,
1045 existing bindings are removed.
1047 Remark: Every sequence of mouse-move-events on a turtle is preceded by a
1048 mouse-click event on that turtle.
1050 >>> turtle.ondrag(turtle.goto)
1051 # Subsequently, clicking and dragging the Turtle will move it across
1052 # the screen thereby producing handdrawings (if pen is down).
1055 Special Turtle methods
1056 ----------------------
1058 .. function:: begin_poly()
1060 Start recording the vertices of a polygon. Current turtle position is first
1064 .. function:: end_poly()
1066 Stop recording the vertices of a polygon. Current turtle position is last
1067 vertex of polygon. This will be connected with the first vertex.
1070 .. function:: get_poly()
1072 Return the last recorded polygon.
1074 >>> p = turtle.get_poly()
1075 >>> turtle.register_shape("myFavouriteShape", p)
1078 .. function:: clone()
1080 Create and return a clone of the turtle with same position, heading and
1084 >>> joe = mick.clone()
1087 .. function:: getturtle()
1089 Return the Turtle object itself. Only reasonable use: as a function to
1090 return the "anonymous turtle":
1092 >>> pet = getturtle()
1095 <turtle.Turtle object at 0x01417350>
1097 [<turtle.Turtle object at 0x01417350>]
1100 .. function:: getscreen()
1102 Return the :class:`TurtleScreen` object the turtle is drawing on.
1103 TurtleScreen methods can then be called for that object.
1105 >>> ts = turtle.getscreen()
1107 <turtle.Screen object at 0x01417710>
1108 >>> ts.bgcolor("pink")
1111 .. function:: setundobuffer(size)
1113 :param size: an integer or ``None``
1115 Set or disable undobuffer. If *size* is an integer an empty undobuffer of
1116 given size is installed. *size* gives the maximum number of turtle actions
1117 that can be undone by the :func:`undo` method/function. If *size* is
1118 ``None``, the undobuffer is disabled.
1120 >>> turtle.setundobuffer(42)
1123 .. function:: undobufferentries()
1125 Return number of entries in the undobuffer.
1127 >>> while undobufferentries():
1131 .. function:: tracer(flag=None, delay=None)
1133 A replica of the corresponding TurtleScreen method.
1138 .. function:: window_width()
1141 Both are replicas of the corresponding TurtleScreen methods.
1148 Excursus about the use of compound shapes
1149 -----------------------------------------
1151 To use compound turtle shapes, which consist of several polygons of different
1152 color, you must use the helper class :class:`Shape` explicitly as described
1155 1. Create an empty Shape object of type "compound".
1156 2. Add as many components to this object as desired, using the
1157 :meth:`addcomponent` method.
1161 >>> s = Shape("compound")
1162 >>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
1163 >>> s.addcomponent(poly1, "red", "blue")
1164 >>> poly2 = ((0,0),(10,-5),(-10,-5))
1165 >>> s.addcomponent(poly2, "blue", "red")
1167 3. Now add the Shape to the Screen's shapelist and use it:
1169 >>> register_shape("myshape", s)
1170 >>> shape("myshape")
1175 The :class:`Shape` class is used internally by the :func:`register_shape`
1176 method in different ways. The application programmer has to deal with the
1177 Shape class *only* when using compound shapes like shown above!
1180 Methods of TurtleScreen/Screen and corresponding functions
1181 ==========================================================
1183 Most of the examples in this section refer to a TurtleScreen instance called
1190 .. function:: bgcolor(*args)
1192 :param args: a color string or three numbers in the range 0..colormode or a
1193 3-tuple of such numbers
1195 Set or return background color of the TurtleScreen.
1197 >>> screen.bgcolor("orange")
1198 >>> screen.bgcolor()
1200 >>> screen.bgcolor(0.5,0,0.5)
1201 >>> screen.bgcolor()
1205 .. function:: bgpic(picname=None)
1207 :param picname: a string, name of a gif-file or ``"nopic"``, or ``None``
1209 Set background image or return name of current backgroundimage. If *picname*
1210 is a filename, set the corresponding image as background. If *picname* is
1211 ``"nopic"``, delete background image, if present. If *picname* is ``None``,
1212 return the filename of the current backgroundimage.
1216 >>> screen.bgpic("landscape.gif")
1221 .. function:: clear()
1224 Delete all drawings and all turtles from the TurtleScreen. Reset the now
1225 empty TurtleScreen to its initial state: white background, no background
1226 image, no event bindings and tracing on.
1229 This TurtleScreen method is available as a global function only under the
1230 name ``clearscreen``. The global function ``clear`` is another one
1231 derived from the Turtle method ``clear``.
1234 .. function:: reset()
1237 Reset all Turtles on the Screen to their initial state.
1240 This TurtleScreen method is available as a global function only under the
1241 name ``resetscreen``. The global function ``reset`` is another one
1242 derived from the Turtle method ``reset``.
1245 .. function:: screensize(canvwidth=None, canvheight=None, bg=None)
1247 :param canvwidth: positive integer, new width of canvas in pixels
1248 :param canvheight: positive integer, new height of canvas in pixels
1249 :param bg: colorstring or color-tupel, new background color
1251 If no arguments are given, return current (canvaswidth, canvasheight). Else
1252 resize the canvas the turtles are drawing on. Do not alter the drawing
1253 window. To observe hidden parts of the canvas, use the scrollbars. With this
1254 method, one can make visible those parts of a drawing which were outside the
1257 >>> turtle.screensize(2000,1500)
1258 # e.g. to search for an erroneously escaped turtle ;-)
1261 .. function:: setworldcoordinates(llx, lly, urx, ury)
1263 :param llx: a number, x-coordinate of lower left corner of canvas
1264 :param lly: a number, y-coordinate of lower left corner of canvas
1265 :param urx: a number, x-coordinate of upper right corner of canvas
1266 :param ury: a number, y-coordinate of upper right corner of canvas
1268 Set up user-defined coordinate system and switch to mode "world" if
1269 necessary. This performs a ``screen.reset()``. If mode "world" is already
1270 active, all drawings are redrawn according to the new coordinates.
1272 **ATTENTION**: in user-defined coordinate systems angles may appear
1276 >>> screen.setworldcoordinates(-50,-7.5,50,7.5)
1277 >>> for _ in range(72):
1280 >>> for _ in range(8):
1281 ... left(45); fd(2) # a regular octagon
1287 .. function:: delay(delay=None)
1289 :param delay: positive integer
1291 Set or return the drawing *delay* in milliseconds. (This is approximately
1292 the time interval between two consecutive canvas updates.) The longer the
1293 drawing delay, the slower the animation.
1297 >>> screen.delay(15)
1302 .. function:: tracer(n=None, delay=None)
1304 :param n: nonnegative integer
1305 :param delay: nonnegative integer
1307 Turn turtle animation on/off and set delay for update drawings. If *n* is
1308 given, only each n-th regular screen update is really performed. (Can be
1309 used to accelerate the drawing of complex graphics.) Second argument sets
1310 delay value (see :func:`delay`).
1312 >>> screen.tracer(8, 25)
1314 >>> for i in range(200):
1320 .. function:: update()
1322 Perform a TurtleScreen update. To be used when tracer is turned off.
1324 See also the RawTurtle/Turtle method :func:`speed`.
1330 .. function:: listen(xdummy=None, ydummy=None)
1332 Set focus on TurtleScreen (in order to collect key-events). Dummy arguments
1333 are provided in order to be able to pass :func:`listen` to the onclick method.
1336 .. function:: onkey(fun, key)
1338 :param fun: a function with no arguments or ``None``
1339 :param key: a string: key (e.g. "a") or key-symbol (e.g. "space")
1341 Bind *fun* to key-release event of key. If *fun* is ``None``, event bindings
1342 are removed. Remark: in order to be able to register key-events, TurtleScreen
1343 must have the focus. (See method :func:`listen`.)
1349 >>> screen.onkey(f, "Up")
1353 .. function:: onclick(fun, btn=1, add=None)
1354 onscreenclick(fun, btn=1, add=None)
1356 :param fun: a function with two arguments which will be called with the
1357 coordinates of the clicked point on the canvas
1358 :param num: number of the mouse-button, defaults to 1 (left mouse button)
1359 :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1360 added, otherwise it will replace a former binding
1362 Bind *fun* to mouse-click events on this screen. If *fun* is ``None``,
1363 existing bindings are removed.
1365 Example for a TurtleScreen instance named ``screen`` and a Turtle instance
1368 >>> screen.onclick(turtle.goto)
1369 # Subsequently clicking into the TurtleScreen will
1370 # make the turtle move to the clicked point.
1371 >>> screen.onclick(None) # remove event binding again
1374 This TurtleScreen method is available as a global function only under the
1375 name ``onscreenclick``. The global function ``onclick`` is another one
1376 derived from the Turtle method ``onclick``.
1379 .. function:: ontimer(fun, t=0)
1381 :param fun: a function with no arguments
1382 :param t: a number >= 0
1384 Install a timer that calls *fun* after *t* milliseconds.
1391 screen.ontimer(f, 250)
1392 >>> f() ### makes the turtle marching around
1396 Settings and special methods
1397 ----------------------------
1399 .. function:: mode(mode=None)
1401 :param mode: one of the strings "standard", "logo" or "world"
1403 Set turtle mode ("standard", "logo" or "world") and perform reset. If mode
1404 is not given, current mode is returned.
1406 Mode "standard" is compatible with old :mod:`turtle`. Mode "logo" is
1407 compatible with most Logo turtle graphics. Mode "world" uses user-defined
1408 "world coordinates". **Attention**: in this mode angles appear distorted if
1409 ``x/y`` unit-ratio doesn't equal 1.
1411 ============ ========================= ===================
1412 Mode Initial turtle heading positive angles
1413 ============ ========================= ===================
1414 "standard" to the right (east) counterclockwise
1415 "logo" upward (north) clockwise
1416 ============ ========================= ===================
1418 >>> mode("logo") # resets turtle heading to north
1423 .. function:: colormode(cmode=None)
1425 :param cmode: one of the values 1.0 or 255
1427 Return the colormode or set it to 1.0 or 255. Subsequently *r*, *g*, *b*
1428 values of color triples have to be in the range 0..\ *cmode*.
1430 >>> screen.colormode()
1432 >>> screen.colormode(255)
1433 >>> turtle.pencolor(240,160,80)
1436 .. function:: getcanvas()
1438 Return the Canvas of this TurtleScreen. Useful for insiders who know what to
1439 do with a Tkinter Canvas.
1441 >>> cv = screen.getcanvas()
1443 <turtle.ScrolledCanvas instance at 0x010742D8>
1446 .. function:: getshapes()
1448 Return a list of names of all currently available turtle shapes.
1450 >>> screen.getshapes()
1451 ["arrow", "blank", "circle", ..., "turtle"]
1454 .. function:: register_shape(name, shape=None)
1455 addshape(name, shape=None)
1457 There are three different ways to call this function:
1459 (1) *name* is the name of a gif-file and *shape* is ``None``: Install the
1460 corresponding image shape.
1463 Image shapes *do not* rotate when turning the turtle, so they do not
1464 display the heading of the turtle!
1466 (2) *name* is an arbitrary string and *shape* is a tuple of pairs of
1467 coordinates: Install the corresponding polygon shape.
1469 (3) *name* is an arbitrary string and shape is a (compound) :class:`Shape`
1470 object: Install the corresponding compound shape.
1472 Add a turtle shape to TurtleScreen's shapelist. Only thusly registered
1473 shapes can be used by issuing the command ``shape(shapename)``.
1475 >>> screen.register_shape("turtle.gif")
1476 >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
1479 .. function:: turtles()
1481 Return the list of turtles on the screen.
1483 >>> for turtle in screen.turtles()
1484 ... turtle.color("red")
1487 .. function:: window_height()
1489 Return the height of the turtle window.
1491 >>> screen.window_height()
1495 .. function:: window_width()
1497 Return the width of the turtle window.
1499 >>> screen.window_width()
1505 Methods specific to Screen, not inherited from TurtleScreen
1506 -----------------------------------------------------------
1510 Shut the turtlegraphics window.
1513 .. function:: exitonclick()
1515 Bind bye() method to mouse clicks on the Screen.
1518 If the value "using_IDLE" in the configuration dictionary is ``False``
1519 (default value), also enter mainloop. Remark: If IDLE with the ``-n`` switch
1520 (no subprocess) is used, this value should be set to ``True`` in
1521 :file:`turtle.cfg`. In this case IDLE's own mainloop is active also for the
1525 .. function:: setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])
1527 Set the size and position of the main window. Default values of arguments
1528 are stored in the configuration dicionary and can be changed via a
1529 :file:`turtle.cfg` file.
1531 :param width: if an integer, a size in pixels, if a float, a fraction of the
1532 screen; default is 50% of screen
1533 :param height: if an integer, the height in pixels, if a float, a fraction of
1534 the screen; default is 75% of screen
1535 :param startx: if positive, starting position in pixels from the left
1536 edge of the screen, if negative from the right edge, if None,
1537 center window horizontally
1538 :param startx: if positive, starting position in pixels from the top
1539 edge of the screen, if negative from the bottom edge, if None,
1540 center window vertically
1542 >>> screen.setup (width=200, height=200, startx=0, starty=0)
1543 # sets window to 200x200 pixels, in upper left of screen
1544 >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
1545 # sets window to 75% of screen by 50% of screen and centers
1548 .. function:: title(titlestring)
1550 :param titlestring: a string that is shown in the titlebar of the turtle
1553 Set title of turtle window to *titlestring*.
1555 >>> screen.title("Welcome to the turtle zoo!")
1558 The public classes of the module :mod:`turtle`
1559 ==============================================
1562 .. class:: RawTurtle(canvas)
1565 :param canvas: a :class:`Tkinter.Canvas`, a :class:`ScrolledCanvas` or a
1566 :class:`TurtleScreen`
1568 Create a turtle. The turtle has all methods described above as "methods of
1574 Subclass of RawTurtle, has the same interface but draws on a default
1575 :class:`Screen` object created automatically when needed for the first time.
1578 .. class:: TurtleScreen(cv)
1580 :param cv: a :class:`Tkinter.Canvas`
1582 Provides screen oriented methods like :func:`setbg` etc. that are described
1587 Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`.
1590 .. class:: ScrolledCavas(master)
1592 :param master: some Tkinter widget to contain the ScrolledCanvas, i.e.
1593 a Tkinter-canvas with scrollbars added
1595 Used by class Screen, which thus automatically provides a ScrolledCanvas as
1596 playground for the turtles.
1598 .. class:: Shape(type_, data)
1600 :param type\_: one of the strings "polygon", "image", "compound"
1602 Data structure modeling shapes. The pair ``(type_, data)`` must follow this
1606 =========== ===========
1608 =========== ===========
1609 "polygon" a polygon-tuple, i.e. a tuple of pairs of coordinates
1610 "image" an image (in this form only used internally!)
1611 "compound" ``None`` (a compund shape has to be constructed using the
1612 :meth:`addcomponent` method)
1613 =========== ===========
1615 .. method:: addcomponent(poly, fill, outline=None)
1617 :param poly: a polygon, i.e. a tuple of pairs of numbers
1618 :param fill: a color the *poly* will be filled with
1619 :param outline: a color for the poly's outline (if given)
1623 >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
1624 >>> s = Shape("compound")
1625 >>> s.addcomponent(poly, "red", "blue")
1626 # .. add more components and then use register_shape()
1628 See :ref:`compoundshapes`.
1631 .. class:: Vec2D(x, y)
1633 A two-dimensional vector class, used as a helper class for implementing
1634 turtle graphics. May be useful for turtle graphics programs too. Derived
1635 from tuple, so a vector is a tuple!
1637 Provides (for *a*, *b* vectors, *k* number):
1639 * ``a + b`` vector addition
1640 * ``a - b`` vector subtraction
1641 * ``a * b`` inner product
1642 * ``k * a`` and ``a * k`` multiplication with scalar
1643 * ``abs(a)`` absolute value of a
1644 * ``a.rotate(angle)`` rotation
1647 Help and configuration
1648 ======================
1653 The public methods of the Screen and Turtle classes are documented extensively
1654 via docstrings. So these can be used as online-help via the Python help
1657 - When using IDLE, tooltips show the signatures and first lines of the
1658 docstrings of typed in function-/method calls.
1660 - Calling :func:`help` on methods or functions displays the docstrings::
1662 >>> help(Screen.bgcolor)
1663 Help on method bgcolor in module turtle:
1665 bgcolor(self, *args) unbound turtle.Screen method
1666 Set or return backgroundcolor of the TurtleScreen.
1668 Arguments (if given): a color string or three numbers
1669 in the range 0..colormode or a 3-tuple of such numbers.
1672 >>> screen.bgcolor("orange")
1673 >>> screen.bgcolor()
1675 >>> screen.bgcolor(0.5,0,0.5)
1676 >>> screen.bgcolor()
1679 >>> help(Turtle.penup)
1680 Help on method penup in module turtle:
1682 penup(self) unbound turtle.Turtle method
1683 Pull the pen up -- no drawing when moving.
1685 Aliases: penup | pu | up
1691 - The docstrings of the functions which are derived from methods have a modified
1695 Help on function bgcolor in module turtle:
1698 Set or return backgroundcolor of the TurtleScreen.
1700 Arguments (if given): a color string or three numbers
1701 in the range 0..colormode or a 3-tuple of such numbers.
1705 >>> bgcolor("orange")
1708 >>> bgcolor(0.5,0,0.5)
1713 Help on function penup in module turtle:
1716 Pull the pen up -- no drawing when moving.
1718 Aliases: penup | pu | up
1725 These modified docstrings are created automatically together with the function
1726 definitions that are derived from the methods at import time.
1729 Translation of docstrings into different languages
1730 --------------------------------------------------
1732 There is a utility to create a dictionary the keys of which are the method names
1733 and the values of which are the docstrings of the public methods of the classes
1736 .. function:: write_docstringdict(filename="turtle_docstringdict")
1738 :param filename: a string, used as filename
1740 Create and write docstring-dictionary to a Python script with the given
1741 filename. This function has to be called explicitly (it is not used by the
1742 turtle graphics classes). The docstring dictionary will be written to the
1743 Python script :file:`{filename}.py`. It is intended to serve as a template
1744 for translation of the docstrings into different languages.
1746 If you (or your students) want to use :mod:`turtle` with online help in your
1747 native language, you have to translate the docstrings and save the resulting
1748 file as e.g. :file:`turtle_docstringdict_german.py`.
1750 If you have an appropriate entry in your :file:`turtle.cfg` file this dictionary
1751 will be read in at import time and will replace the original English docstrings.
1753 At the time of this writing there are docstring dictionaries in German and in
1754 Italian. (Requests please to glingl@aon.at.)
1758 How to configure Screen and Turtles
1759 -----------------------------------
1761 The built-in default configuration mimics the appearance and behaviour of the
1762 old turtle module in order to retain best possible compatibility with it.
1764 If you want to use a different configuration which better reflects the features
1765 of this module or which better fits to your needs, e.g. for use in a classroom,
1766 you can prepare a configuration file ``turtle.cfg`` which will be read at import
1767 time and modify the configuration according to its settings.
1769 The built in configuration would correspond to the following turtle.cfg::
1780 undobuffersize = 1000
1784 resizemode = noresize
1787 exampleturtle = turtle
1788 examplescreen = screen
1789 title = Python Turtle Graphics
1792 Short explanation of selected entries:
1794 - The first four lines correspond to the arguments of the :meth:`Screen.setup`
1796 - Line 5 and 6 correspond to the arguments of the method
1797 :meth:`Screen.screensize`.
1798 - *shape* can be any of the built-in shapes, e.g: arrow, turtle, etc. For more
1799 info try ``help(shape)``.
1800 - If you want to use no fillcolor (i.e. make the turtle transparent), you have
1801 to write ``fillcolor = ""`` (but all nonempty strings must not have quotes in
1803 - If you want to reflect the turtle its state, you have to use ``resizemode =
1805 - If you set e.g. ``language = italian`` the docstringdict
1806 :file:`turtle_docstringdict_italian.py` will be loaded at import time (if
1807 present on the import path, e.g. in the same directory as :mod:`turtle`.
1808 - The entries *exampleturtle* and *examplescreen* define the names of these
1809 objects as they occur in the docstrings. The transformation of
1810 method-docstrings to function-docstrings will delete these names from the
1812 - *using_IDLE*: Set this to ``True`` if you regularly work with IDLE and its -n
1813 switch ("no subprocess"). This will prevent :func:`exitonclick` to enter the
1816 There can be a :file:`turtle.cfg` file in the directory where :mod:`turtle` is
1817 stored and an additional one in the current working directory. The latter will
1818 override the settings of the first one.
1820 The :file:`Demo/turtle` directory contains a :file:`turtle.cfg` file. You can
1821 study it as an example and see its effects when running the demos (preferably
1822 not from within the demo-viewer).
1828 There is a set of demo scripts in the turtledemo directory located in the
1829 :file:`Demo/turtle` directory in the source distribution.
1833 - a set of 15 demo scripts demonstrating differet features of the new module
1835 - a demo viewer :file:`turtleDemo.py` which can be used to view the sourcecode
1836 of the scripts and run them at the same time. 14 of the examples can be
1837 accessed via the Examples menu; all of them can also be run standalone.
1838 - The example :file:`turtledemo_two_canvases.py` demonstrates the simultaneous
1839 use of two canvases with the turtle module. Therefore it only can be run
1841 - There is a :file:`turtle.cfg` file in this directory, which also serves as an
1842 example for how to write and use such files.
1844 The demoscripts are:
1846 +----------------+------------------------------+-----------------------+
1847 | Name | Description | Features |
1848 +----------------+------------------------------+-----------------------+
1849 | bytedesign | complex classical | :func:`tracer`, delay,|
1850 | | turtlegraphics pattern | :func:`update` |
1851 +----------------+------------------------------+-----------------------+
1852 | chaos | graphs verhust dynamics, | world coordinates |
1853 | | proves that you must not | |
1854 | | trust computers' computations| |
1855 +----------------+------------------------------+-----------------------+
1856 | clock | analog clock showing time | turtles as clock's |
1857 | | of your computer | hands, ontimer |
1858 +----------------+------------------------------+-----------------------+
1859 | colormixer | experiment with r, g, b | :func:`ondrag` |
1860 +----------------+------------------------------+-----------------------+
1861 | fractalcurves | Hilbert & Koch curves | recursion |
1862 +----------------+------------------------------+-----------------------+
1863 | lindenmayer | ethnomathematics | L-System |
1864 | | (indian kolams) | |
1865 +----------------+------------------------------+-----------------------+
1866 | minimal_hanoi | Towers of Hanoi | Rectangular Turtles |
1867 | | | as Hanoi discs |
1868 | | | (shape, shapesize) |
1869 +----------------+------------------------------+-----------------------+
1870 | paint | super minimalistic | :func:`onclick` |
1871 | | drawing program | |
1872 +----------------+------------------------------+-----------------------+
1873 | peace | elementary | turtle: appearance |
1874 | | | and animation |
1875 +----------------+------------------------------+-----------------------+
1876 | penrose | aperiodic tiling with | :func:`stamp` |
1877 | | kites and darts | |
1878 +----------------+------------------------------+-----------------------+
1879 | planet_and_moon| simulation of | compound shapes, |
1880 | | gravitational system | :class:`Vec2D` |
1881 +----------------+------------------------------+-----------------------+
1882 | tree | a (graphical) breadth | :func:`clone` |
1883 | | first tree (using generators)| |
1884 +----------------+------------------------------+-----------------------+
1885 | wikipedia | a pattern from the wikipedia | :func:`clone`, |
1886 | | article on turtle graphics | :func:`undo` |
1887 +----------------+------------------------------+-----------------------+
1888 | yingyang | another elementary example | :func:`circle` |
1889 +----------------+------------------------------+-----------------------+