• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1=================================
2:mod:`turtle` --- Turtle graphics
3=================================
4
5.. module:: turtle
6   :synopsis: An educational framework for simple graphics applications
7
8.. sectionauthor:: Gregor Lingl <gregor.lingl@aon.at>
9
10**Source code:** :source:`Lib/turtle.py`
11
12.. testsetup:: default
13
14   from turtle import *
15   turtle = Turtle()
16
17--------------
18
19Introduction
20============
21
22Turtle graphics is an implementation of `the popular geometric drawing tools
23introduced in Logo <https://en.wikipedia.org/wiki/Turtle_
24(robot)>`_, developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon
25in 1967.
26
27
28Get started
29===========
30
31Imagine a robotic turtle starting at (0, 0) in the x-y plane.  After an ``import turtle``, give it the
32command ``turtle.forward(15)``, and it moves (on-screen!) 15 pixels in the
33direction it is facing, drawing a line as it moves.  Give it the command
34``turtle.right(25)``, and it rotates in-place 25 degrees clockwise.
35
36.. sidebar:: Turtle star
37
38   Turtle can draw intricate shapes using programs that repeat simple
39   moves.
40
41   .. image:: turtle-star.*
42      :align: center
43
44In Python, turtle graphics provides a representation of a physical "turtle"
45(a little robot with a pen) that draws on a sheet of paper on the floor.
46
47It's an effective and well-proven way for learners to encounter
48programming concepts and interaction with software, as it provides instant,
49visible feedback. It also provides convenient access to graphical output
50in general.
51
52Turtle drawing was originally created as an educational tool, to be used by
53teachers in the classroom. For the programmer who needs to produce some
54graphical output it can be a way to do that without the overhead of
55introducing more complex or external libraries into their work.
56
57
58.. _turtle-tutorial:
59
60Tutorial
61========
62
63New users should start here. In this tutorial we'll explore some of the
64basics of turtle drawing.
65
66
67Starting a turtle environment
68-----------------------------
69
70In a Python shell, import all the objects of the ``turtle`` module::
71
72    from turtle import *
73
74If you run into a ``No module named '_tkinter'`` error, you'll have to
75install the :mod:`Tk interface package <tkinter>` on your system.
76
77
78Basic drawing
79-------------
80
81Send the turtle forward 100 steps::
82
83   forward(100)
84
85You should see (most likely, in a new window on your display) a line
86drawn by the turtle, heading East. Change the direction of the turtle,
87so that it turns 120 degrees left (anti-clockwise)::
88
89   left(120)
90
91Let's continue by drawing a triangle::
92
93   forward(100)
94   left(120)
95   forward(100)
96
97Notice how the turtle, represented by an arrow, points in different
98directions as you steer it.
99
100Experiment with those commands, and also with ``backward()`` and
101``right()``.
102
103
104Pen control
105~~~~~~~~~~~
106
107Try changing the color - for example, ``color('blue')`` - and
108width of the line - for example, ``width(3)`` - and then drawing again.
109
110You can also move the turtle around without drawing, by lifting up the pen:
111``up()`` before moving. To start drawing again, use ``down()``.
112
113
114The turtle's position
115~~~~~~~~~~~~~~~~~~~~~
116
117Send your turtle back to its starting-point (useful if it has disappeared
118off-screen)::
119
120   home()
121
122The home position is at the center of the turtle's screen. If you ever need to
123know them, get the turtle's x-y coordinates with::
124
125    pos()
126
127Home is at ``(0, 0)``.
128
129And after a while, it will probably help to clear the window so we can start
130anew::
131
132   clearscreen()
133
134
135Making algorithmic patterns
136---------------------------
137
138Using loops, it's possible to build up geometric patterns::
139
140    for steps in range(100):
141        for c in ('blue', 'red', 'green'):
142            color(c)
143            forward(steps)
144            right(30)
145
146
147\ - which of course, are limited only by the imagination!
148
149Let's draw the star shape at the top of this page. We want red lines,
150filled in with yellow::
151
152    color('red')
153    fillcolor('yellow')
154
155Just as ``up()`` and ``down()`` determine whether lines will be drawn,
156filling can be turned on and off::
157
158    begin_fill()
159
160Next we'll create a loop::
161
162    while True:
163        forward(200)
164        left(170)
165        if abs(pos()) < 1:
166            break
167
168``abs(pos()) < 1`` is a good way to know when the turtle is back at its
169home position.
170
171Finally, complete the filling::
172
173    end_fill()
174
175(Note that filling only actually takes place when you give the
176``end_fill()`` command.)
177
178
179.. _turtle-how-to:
180
181How to...
182=========
183
184This section covers some typical turtle use-cases and approaches.
185
186
187Get started as quickly as possible
188----------------------------------
189
190One of the joys of turtle graphics is the immediate, visual feedback that's
191available from simple commands - it's an excellent way to introduce children
192to programming ideas, with a minimum of overhead (not just children, of
193course).
194
195The turtle module makes this possible by exposing all its basic functionality
196as functions, available with ``from turtle import *``. The :ref:`turtle
197graphics tutorial <turtle-tutorial>` covers this approach.
198
199It's worth noting that many of the turtle commands also have even more terse
200equivalents, such as ``fd()`` for :func:`forward`. These are especially
201useful when working with learners for whom typing is not a skill.
202
203.. _note:
204
205    You'll need to have the :mod:`Tk interface package <tkinter>` installed on
206    your system for turtle graphics to work. Be warned that this is not
207    always straightforward, so check this in advance if you're planning to
208    use turtle graphics with a learner.
209
210
211Use the ``turtle`` module namespace
212-----------------------------------
213
214Using ``from turtle import *`` is convenient - but be warned that it imports a
215rather large collection of objects, and if you're doing anything but turtle
216graphics you run the risk of a name conflict (this becomes even more an issue
217if you're using turtle graphics in a script where other modules might be
218imported).
219
220The solution is to use ``import turtle`` - ``fd()`` becomes
221``turtle.fd()``, ``width()`` becomes ``turtle.width()`` and so on. (If typing
222"turtle" over and over again becomes tedious, use for example ``import turtle
223as t`` instead.)
224
225
226Use turtle graphics in a script
227-------------------------------
228
229It's recommended to use the ``turtle`` module namespace as described
230immediately above, for example::
231
232    import turtle as t
233    from random import random
234
235    for i in range(100):
236        steps = int(random() * 100)
237        angle = int(random() * 360)
238        t.right(angle)
239        t.fd(steps)
240
241Another step is also required though - as soon as the script ends, Python
242will also close the turtle's window. Add::
243
244    t.mainloop()
245
246to the end of the script. The script will now wait to be dismissed and
247will not exit until it is terminated, for example by closing the turtle
248graphics window.
249
250
251Use object-oriented turtle graphics
252-----------------------------------
253
254.. seealso:: :ref:`Explanation of the object-oriented interface <turtle-explanation>`
255
256Other than for very basic introductory purposes, or for trying things out
257as quickly as possible, it's more usual and much more powerful to use the
258object-oriented approach to turtle graphics. For example, this allows
259multiple turtles on screen at once.
260
261In this approach, the various turtle commands are methods of objects (mostly of
262``Turtle`` objects). You *can* use the object-oriented approach in the shell,
263but it would be more typical in a Python script.
264
265The example above then becomes::
266
267    from turtle import Turtle
268    from random import random
269
270    t = Turtle()
271    for i in range(100):
272        steps = int(random() * 100)
273        angle = int(random() * 360)
274        t.right(angle)
275        t.fd(steps)
276
277    t.screen.mainloop()
278
279Note the last line. ``t.screen`` is an instance of the :class:`Screen`
280that a Turtle instance exists on; it's created automatically along with
281the turtle.
282
283The turtle's screen can be customised, for example::
284
285    t.screen.title('Object-oriented turtle demo')
286    t.screen.bgcolor("orange")
287
288
289Turtle graphics reference
290=========================
291
292.. note::
293
294   In the following documentation the argument list for functions is given.
295   Methods, of course, have the additional first argument *self* which is
296   omitted here.
297
298
299Turtle methods
300--------------
301
302Turtle motion
303   Move and draw
304      | :func:`forward` | :func:`fd`
305      | :func:`backward` | :func:`bk` | :func:`back`
306      | :func:`right` | :func:`rt`
307      | :func:`left` | :func:`lt`
308      | :func:`goto` | :func:`setpos` | :func:`setposition`
309      | :func:`teleport`
310      | :func:`setx`
311      | :func:`sety`
312      | :func:`setheading` | :func:`seth`
313      | :func:`home`
314      | :func:`circle`
315      | :func:`dot`
316      | :func:`stamp`
317      | :func:`clearstamp`
318      | :func:`clearstamps`
319      | :func:`undo`
320      | :func:`speed`
321
322   Tell Turtle's state
323      | :func:`position` | :func:`pos`
324      | :func:`towards`
325      | :func:`xcor`
326      | :func:`ycor`
327      | :func:`heading`
328      | :func:`distance`
329
330   Setting and measurement
331      | :func:`degrees`
332      | :func:`radians`
333
334Pen control
335   Drawing state
336      | :func:`pendown` | :func:`pd` | :func:`down`
337      | :func:`penup` | :func:`pu` | :func:`up`
338      | :func:`pensize` | :func:`width`
339      | :func:`pen`
340      | :func:`isdown`
341
342   Color control
343      | :func:`color`
344      | :func:`pencolor`
345      | :func:`fillcolor`
346
347   Filling
348      | :func:`filling`
349      | :func:`begin_fill`
350      | :func:`end_fill`
351
352   More drawing control
353      | :func:`reset`
354      | :func:`clear`
355      | :func:`write`
356
357Turtle state
358   Visibility
359      | :func:`showturtle` | :func:`st`
360      | :func:`hideturtle` | :func:`ht`
361      | :func:`isvisible`
362
363   Appearance
364      | :func:`shape`
365      | :func:`resizemode`
366      | :func:`shapesize` | :func:`turtlesize`
367      | :func:`shearfactor`
368      | :func:`tiltangle`
369      | :func:`tilt`
370      | :func:`shapetransform`
371      | :func:`get_shapepoly`
372
373Using events
374   | :func:`onclick`
375   | :func:`onrelease`
376   | :func:`ondrag`
377
378Special Turtle methods
379   | :func:`begin_poly`
380   | :func:`end_poly`
381   | :func:`get_poly`
382   | :func:`clone`
383   | :func:`getturtle` | :func:`getpen`
384   | :func:`getscreen`
385   | :func:`setundobuffer`
386   | :func:`undobufferentries`
387
388
389Methods of TurtleScreen/Screen
390------------------------------
391
392Window control
393   | :func:`bgcolor`
394   | :func:`bgpic`
395   | :func:`clearscreen`
396   | :func:`resetscreen`
397   | :func:`screensize`
398   | :func:`setworldcoordinates`
399
400Animation control
401   | :func:`delay`
402   | :func:`tracer`
403   | :func:`update`
404
405Using screen events
406   | :func:`listen`
407   | :func:`onkey` | :func:`onkeyrelease`
408   | :func:`onkeypress`
409   | :func:`onclick` | :func:`onscreenclick`
410   | :func:`ontimer`
411   | :func:`mainloop` | :func:`done`
412
413Settings and special methods
414   | :func:`mode`
415   | :func:`colormode`
416   | :func:`getcanvas`
417   | :func:`getshapes`
418   | :func:`register_shape` | :func:`addshape`
419   | :func:`turtles`
420   | :func:`window_height`
421   | :func:`window_width`
422
423Input methods
424   | :func:`textinput`
425   | :func:`numinput`
426
427Methods specific to Screen
428   | :func:`bye`
429   | :func:`exitonclick`
430   | :func:`setup`
431   | :func:`title`
432
433
434Methods of RawTurtle/Turtle and corresponding functions
435=======================================================
436
437Most of the examples in this section refer to a Turtle instance called
438``turtle``.
439
440Turtle motion
441-------------
442
443.. function:: forward(distance)
444              fd(distance)
445
446   :param distance: a number (integer or float)
447
448   Move the turtle forward by the specified *distance*, in the direction the
449   turtle is headed.
450
451   .. doctest::
452      :skipif: _tkinter is None
453
454      >>> turtle.position()
455      (0.00,0.00)
456      >>> turtle.forward(25)
457      >>> turtle.position()
458      (25.00,0.00)
459      >>> turtle.forward(-75)
460      >>> turtle.position()
461      (-50.00,0.00)
462
463
464.. function:: back(distance)
465              bk(distance)
466              backward(distance)
467
468   :param distance: a number
469
470   Move the turtle backward by *distance*, opposite to the direction the
471   turtle is headed.  Do not change the turtle's heading.
472
473   .. doctest::
474      :hide:
475
476      >>> turtle.goto(0, 0)
477
478   .. doctest::
479      :skipif: _tkinter is None
480
481      >>> turtle.position()
482      (0.00,0.00)
483      >>> turtle.backward(30)
484      >>> turtle.position()
485      (-30.00,0.00)
486
487
488.. function:: right(angle)
489              rt(angle)
490
491   :param angle: a number (integer or float)
492
493   Turn turtle right by *angle* units.  (Units are by default degrees, but
494   can be set via the :func:`degrees` and :func:`radians` functions.)  Angle
495   orientation depends on the turtle mode, see :func:`mode`.
496
497   .. doctest::
498      :skipif: _tkinter is None
499      :hide:
500
501      >>> turtle.setheading(22)
502
503   .. doctest::
504      :skipif: _tkinter is None
505
506      >>> turtle.heading()
507      22.0
508      >>> turtle.right(45)
509      >>> turtle.heading()
510      337.0
511
512
513.. function:: left(angle)
514              lt(angle)
515
516   :param angle: a number (integer or float)
517
518   Turn turtle left by *angle* units.  (Units are by default degrees, but
519   can be set via the :func:`degrees` and :func:`radians` functions.)  Angle
520   orientation depends on the turtle mode, see :func:`mode`.
521
522   .. doctest::
523      :skipif: _tkinter is None
524      :hide:
525
526      >>> turtle.setheading(22)
527
528   .. doctest::
529      :skipif: _tkinter is None
530
531      >>> turtle.heading()
532      22.0
533      >>> turtle.left(45)
534      >>> turtle.heading()
535      67.0
536
537
538.. function:: goto(x, y=None)
539              setpos(x, y=None)
540              setposition(x, y=None)
541
542   :param x: a number or a pair/vector of numbers
543   :param y: a number or ``None``
544
545   If *y* is ``None``, *x* must be a pair of coordinates or a :class:`Vec2D`
546   (e.g. as returned by :func:`pos`).
547
548   Move turtle to an absolute position.  If the pen is down, draw line.  Do
549   not change the turtle's orientation.
550
551   .. doctest::
552      :skipif: _tkinter is None
553      :hide:
554
555      >>> turtle.goto(0, 0)
556
557   .. doctest::
558      :skipif: _tkinter is None
559
560      >>> tp = turtle.pos()
561      >>> tp
562      (0.00,0.00)
563      >>> turtle.setpos(60,30)
564      >>> turtle.pos()
565      (60.00,30.00)
566      >>> turtle.setpos((20,80))
567      >>> turtle.pos()
568      (20.00,80.00)
569      >>> turtle.setpos(tp)
570      >>> turtle.pos()
571      (0.00,0.00)
572
573
574.. function:: teleport(x, y=None, *, fill_gap=False)
575
576   :param x: a number or ``None``
577   :param y: a number or ``None``
578   :param fill_gap: a boolean
579
580   Move turtle to an absolute position. Unlike goto(x, y), a line will not
581   be drawn. The turtle's orientation does not change. If currently
582   filling, the polygon(s) teleported from will be filled after leaving,
583   and filling will begin again after teleporting. This can be disabled
584   with fill_gap=True, which makes the imaginary line traveled during
585   teleporting act as a fill barrier like in goto(x, y).
586
587   .. doctest::
588      :skipif: _tkinter is None
589      :hide:
590
591      >>> turtle.goto(0, 0)
592
593   .. doctest::
594      :skipif: _tkinter is None
595
596      >>> tp = turtle.pos()
597      >>> tp
598      (0.00,0.00)
599      >>> turtle.teleport(60)
600      >>> turtle.pos()
601      (60.00,0.00)
602      >>> turtle.teleport(y=10)
603      >>> turtle.pos()
604      (60.00,10.00)
605      >>> turtle.teleport(20, 30)
606      >>> turtle.pos()
607      (20.00,30.00)
608
609   .. versionadded:: 3.12
610
611
612.. function:: setx(x)
613
614   :param x: a number (integer or float)
615
616   Set the turtle's first coordinate to *x*, leave second coordinate
617   unchanged.
618
619   .. doctest::
620      :skipif: _tkinter is None
621      :hide:
622
623      >>> turtle.goto(0, 240)
624
625   .. doctest::
626      :skipif: _tkinter is None
627
628      >>> turtle.position()
629      (0.00,240.00)
630      >>> turtle.setx(10)
631      >>> turtle.position()
632      (10.00,240.00)
633
634
635.. function:: sety(y)
636
637   :param y: a number (integer or float)
638
639   Set the turtle's second coordinate to *y*, leave first coordinate unchanged.
640
641   .. doctest::
642      :skipif: _tkinter is None
643      :hide:
644
645      >>> turtle.goto(0, 40)
646
647   .. doctest::
648      :skipif: _tkinter is None
649
650      >>> turtle.position()
651      (0.00,40.00)
652      >>> turtle.sety(-10)
653      >>> turtle.position()
654      (0.00,-10.00)
655
656
657.. function:: setheading(to_angle)
658              seth(to_angle)
659
660   :param to_angle: a number (integer or float)
661
662   Set the orientation of the turtle to *to_angle*.  Here are some common
663   directions in degrees:
664
665   =================== ====================
666    standard mode           logo mode
667   =================== ====================
668      0 - east                0 - north
669     90 - north              90 - east
670    180 - west              180 - south
671    270 - south             270 - west
672   =================== ====================
673
674   .. doctest::
675      :skipif: _tkinter is None
676
677      >>> turtle.setheading(90)
678      >>> turtle.heading()
679      90.0
680
681
682.. function:: home()
683
684   Move turtle to the origin -- coordinates (0,0) -- and set its heading to
685   its start-orientation (which depends on the mode, see :func:`mode`).
686
687   .. doctest::
688      :skipif: _tkinter is None
689      :hide:
690
691      >>> turtle.setheading(90)
692      >>> turtle.goto(0, -10)
693
694   .. doctest::
695      :skipif: _tkinter is None
696
697      >>> turtle.heading()
698      90.0
699      >>> turtle.position()
700      (0.00,-10.00)
701      >>> turtle.home()
702      >>> turtle.position()
703      (0.00,0.00)
704      >>> turtle.heading()
705      0.0
706
707
708.. function:: circle(radius, extent=None, steps=None)
709
710   :param radius: a number
711   :param extent: a number (or ``None``)
712   :param steps: an integer (or ``None``)
713
714   Draw a circle with given *radius*.  The center is *radius* units left of
715   the turtle; *extent* -- an angle -- determines which part of the circle
716   is drawn.  If *extent* is not given, draw the entire circle.  If *extent*
717   is not a full circle, one endpoint of the arc is the current pen
718   position.  Draw the arc in counterclockwise direction if *radius* is
719   positive, otherwise in clockwise direction.  Finally the direction of the
720   turtle is changed by the amount of *extent*.
721
722   As the circle is approximated by an inscribed regular polygon, *steps*
723   determines the number of steps to use.  If not given, it will be
724   calculated automatically.  May be used to draw regular polygons.
725
726   .. doctest::
727      :skipif: _tkinter is None
728
729      >>> turtle.home()
730      >>> turtle.position()
731      (0.00,0.00)
732      >>> turtle.heading()
733      0.0
734      >>> turtle.circle(50)
735      >>> turtle.position()
736      (-0.00,0.00)
737      >>> turtle.heading()
738      0.0
739      >>> turtle.circle(120, 180)  # draw a semicircle
740      >>> turtle.position()
741      (0.00,240.00)
742      >>> turtle.heading()
743      180.0
744
745
746.. function:: dot(size=None, *color)
747
748   :param size: an integer >= 1 (if given)
749   :param color: a colorstring or a numeric color tuple
750
751   Draw a circular dot with diameter *size*, using *color*.  If *size* is
752   not given, the maximum of pensize+4 and 2*pensize is used.
753
754
755   .. doctest::
756      :skipif: _tkinter is None
757
758      >>> turtle.home()
759      >>> turtle.dot()
760      >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
761      >>> turtle.position()
762      (100.00,-0.00)
763      >>> turtle.heading()
764      0.0
765
766
767.. function:: stamp()
768
769   Stamp a copy of the turtle shape onto the canvas at the current turtle
770   position.  Return a stamp_id for that stamp, which can be used to delete
771   it by calling ``clearstamp(stamp_id)``.
772
773   .. doctest::
774      :skipif: _tkinter is None
775
776      >>> turtle.color("blue")
777      >>> stamp_id = turtle.stamp()
778      >>> turtle.fd(50)
779
780
781.. function:: clearstamp(stampid)
782
783   :param stampid: an integer, must be return value of previous
784                   :func:`stamp` call
785
786   Delete stamp with given *stampid*.
787
788   .. doctest::
789      :skipif: _tkinter is None
790
791      >>> turtle.position()
792      (150.00,-0.00)
793      >>> turtle.color("blue")
794      >>> astamp = turtle.stamp()
795      >>> turtle.fd(50)
796      >>> turtle.position()
797      (200.00,-0.00)
798      >>> turtle.clearstamp(astamp)
799      >>> turtle.position()
800      (200.00,-0.00)
801
802
803.. function:: clearstamps(n=None)
804
805   :param n: an integer (or ``None``)
806
807   Delete all or first/last *n* of turtle's stamps.  If *n* is ``None``, delete
808   all stamps, if *n* > 0 delete first *n* stamps, else if *n* < 0 delete
809   last *n* stamps.
810
811   .. doctest::
812
813      >>> for i in range(8):
814      ...     unused_stamp_id = turtle.stamp()
815      ...     turtle.fd(30)
816      >>> turtle.clearstamps(2)
817      >>> turtle.clearstamps(-2)
818      >>> turtle.clearstamps()
819
820
821.. function:: undo()
822
823   Undo (repeatedly) the last turtle action(s).  Number of available
824   undo actions is determined by the size of the undobuffer.
825
826   .. doctest::
827      :skipif: _tkinter is None
828
829      >>> for i in range(4):
830      ...     turtle.fd(50); turtle.lt(80)
831      ...
832      >>> for i in range(8):
833      ...     turtle.undo()
834
835
836.. function:: speed(speed=None)
837
838   :param speed: an integer in the range 0..10 or a speedstring (see below)
839
840   Set the turtle's speed to an integer value in the range 0..10.  If no
841   argument is given, return current speed.
842
843   If input is a number greater than 10 or smaller than 0.5, speed is set
844   to 0.  Speedstrings are mapped to speedvalues as follows:
845
846   * "fastest":  0
847   * "fast":  10
848   * "normal":  6
849   * "slow":  3
850   * "slowest":  1
851
852   Speeds from 1 to 10 enforce increasingly faster animation of line drawing
853   and turtle turning.
854
855   Attention: *speed* = 0 means that *no* animation takes
856   place. forward/back makes turtle jump and likewise left/right make the
857   turtle turn instantly.
858
859   .. doctest::
860      :skipif: _tkinter is None
861
862      >>> turtle.speed()
863      3
864      >>> turtle.speed('normal')
865      >>> turtle.speed()
866      6
867      >>> turtle.speed(9)
868      >>> turtle.speed()
869      9
870
871
872Tell Turtle's state
873-------------------
874
875.. function:: position()
876              pos()
877
878   Return the turtle's current location (x,y) (as a :class:`Vec2D` vector).
879
880   .. doctest::
881      :skipif: _tkinter is None
882
883      >>> turtle.pos()
884      (440.00,-0.00)
885
886
887.. function:: towards(x, y=None)
888
889   :param x: a number or a pair/vector of numbers or a turtle instance
890   :param y: a number if *x* is a number, else ``None``
891
892   Return the angle between the line from turtle position to position specified
893   by (x,y), the vector or the other turtle.  This depends on the turtle's start
894   orientation which depends on the mode - "standard"/"world" or "logo".
895
896   .. doctest::
897      :skipif: _tkinter is None
898
899      >>> turtle.goto(10, 10)
900      >>> turtle.towards(0,0)
901      225.0
902
903
904.. function:: xcor()
905
906   Return the turtle's x coordinate.
907
908   .. doctest::
909      :skipif: _tkinter is None
910
911      >>> turtle.home()
912      >>> turtle.left(50)
913      >>> turtle.forward(100)
914      >>> turtle.pos()
915      (64.28,76.60)
916      >>> print(round(turtle.xcor(), 5))
917      64.27876
918
919
920.. function:: ycor()
921
922   Return the turtle's y coordinate.
923
924   .. doctest::
925      :skipif: _tkinter is None
926
927      >>> turtle.home()
928      >>> turtle.left(60)
929      >>> turtle.forward(100)
930      >>> print(turtle.pos())
931      (50.00,86.60)
932      >>> print(round(turtle.ycor(), 5))
933      86.60254
934
935
936.. function:: heading()
937
938   Return the turtle's current heading (value depends on the turtle mode, see
939   :func:`mode`).
940
941   .. doctest::
942      :skipif: _tkinter is None
943
944      >>> turtle.home()
945      >>> turtle.left(67)
946      >>> turtle.heading()
947      67.0
948
949
950.. function:: distance(x, y=None)
951
952   :param x: a number or a pair/vector of numbers or a turtle instance
953   :param y: a number if *x* is a number, else ``None``
954
955   Return the distance from the turtle to (x,y), the given vector, or the given
956   other turtle, in turtle step units.
957
958   .. doctest::
959      :skipif: _tkinter is None
960
961      >>> turtle.home()
962      >>> turtle.distance(30,40)
963      50.0
964      >>> turtle.distance((30,40))
965      50.0
966      >>> joe = Turtle()
967      >>> joe.forward(77)
968      >>> turtle.distance(joe)
969      77.0
970
971
972Settings for measurement
973------------------------
974
975.. function:: degrees(fullcircle=360.0)
976
977   :param fullcircle: a number
978
979   Set angle measurement units, i.e. set number of "degrees" for a full circle.
980   Default value is 360 degrees.
981
982   .. doctest::
983      :skipif: _tkinter is None
984
985      >>> turtle.home()
986      >>> turtle.left(90)
987      >>> turtle.heading()
988      90.0
989
990      Change angle measurement unit to grad (also known as gon,
991      grade, or gradian and equals 1/100-th of the right angle.)
992      >>> turtle.degrees(400.0)
993      >>> turtle.heading()
994      100.0
995      >>> turtle.degrees(360)
996      >>> turtle.heading()
997      90.0
998
999
1000.. function:: radians()
1001
1002   Set the angle measurement units to radians.  Equivalent to
1003   ``degrees(2*math.pi)``.
1004
1005   .. doctest::
1006      :skipif: _tkinter is None
1007
1008      >>> turtle.home()
1009      >>> turtle.left(90)
1010      >>> turtle.heading()
1011      90.0
1012      >>> turtle.radians()
1013      >>> turtle.heading()
1014      1.5707963267948966
1015
1016   .. doctest::
1017      :skipif: _tkinter is None
1018      :hide:
1019
1020      >>> turtle.degrees(360)
1021
1022
1023Pen control
1024-----------
1025
1026Drawing state
1027~~~~~~~~~~~~~
1028
1029.. function:: pendown()
1030              pd()
1031              down()
1032
1033   Pull the pen down -- drawing when moving.
1034
1035
1036.. function:: penup()
1037              pu()
1038              up()
1039
1040   Pull the pen up -- no drawing when moving.
1041
1042
1043.. function:: pensize(width=None)
1044              width(width=None)
1045
1046   :param width: a positive number
1047
1048   Set the line thickness to *width* or return it.  If resizemode is set to
1049   "auto" and turtleshape is a polygon, that polygon is drawn with the same line
1050   thickness.  If no argument is given, the current pensize is returned.
1051
1052   .. doctest::
1053      :skipif: _tkinter is None
1054
1055      >>> turtle.pensize()
1056      1
1057      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn
1058
1059
1060.. function:: pen(pen=None, **pendict)
1061
1062   :param pen: a dictionary with some or all of the below listed keys
1063   :param pendict: one or more keyword-arguments with the below listed keys as keywords
1064
1065   Return or set the pen's attributes in a "pen-dictionary" with the following
1066   key/value pairs:
1067
1068   * "shown": True/False
1069   * "pendown": True/False
1070   * "pencolor": color-string or color-tuple
1071   * "fillcolor": color-string or color-tuple
1072   * "pensize": positive number
1073   * "speed": number in range 0..10
1074   * "resizemode": "auto" or "user" or "noresize"
1075   * "stretchfactor": (positive number, positive number)
1076   * "outline": positive number
1077   * "tilt": number
1078
1079   This dictionary can be used as argument for a subsequent call to :func:`pen`
1080   to restore the former pen-state.  Moreover one or more of these attributes
1081   can be provided as keyword-arguments.  This can be used to set several pen
1082   attributes in one statement.
1083
1084   .. doctest::
1085      :skipif: _tkinter is None
1086      :options: +NORMALIZE_WHITESPACE
1087
1088      >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
1089      >>> sorted(turtle.pen().items())
1090      [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
1091       ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
1092       ('shearfactor', 0.0), ('shown', True), ('speed', 9),
1093       ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]
1094      >>> penstate=turtle.pen()
1095      >>> turtle.color("yellow", "")
1096      >>> turtle.penup()
1097      >>> sorted(turtle.pen().items())[:3]
1098      [('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')]
1099      >>> turtle.pen(penstate, fillcolor="green")
1100      >>> sorted(turtle.pen().items())[:3]
1101      [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]
1102
1103.. function:: isdown()
1104
1105   Return ``True`` if pen is down, ``False`` if it's up.
1106
1107   .. doctest::
1108      :skipif: _tkinter is None
1109
1110      >>> turtle.penup()
1111      >>> turtle.isdown()
1112      False
1113      >>> turtle.pendown()
1114      >>> turtle.isdown()
1115      True
1116
1117
1118Color control
1119~~~~~~~~~~~~~
1120
1121.. function:: pencolor(*args)
1122
1123   Return or set the pencolor.
1124
1125   Four input formats are allowed:
1126
1127   ``pencolor()``
1128      Return the current pencolor as color specification string or
1129      as a tuple (see example).  May be used as input to another
1130      color/pencolor/fillcolor call.
1131
1132   ``pencolor(colorstring)``
1133      Set pencolor to *colorstring*, which is a Tk color specification string,
1134      such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
1135
1136   ``pencolor((r, g, b))``
1137      Set pencolor to the RGB color represented by the tuple of *r*, *g*, and
1138      *b*.  Each of *r*, *g*, and *b* must be in the range 0..colormode, where
1139      colormode is either 1.0 or 255 (see :func:`colormode`).
1140
1141   ``pencolor(r, g, b)``
1142      Set pencolor to the RGB color represented by *r*, *g*, and *b*.  Each of
1143      *r*, *g*, and *b* must be in the range 0..colormode.
1144
1145   If turtleshape is a polygon, the outline of that polygon is drawn with the
1146   newly set pencolor.
1147
1148   .. doctest::
1149      :skipif: _tkinter is None
1150
1151      >>> colormode()
1152      1.0
1153      >>> turtle.pencolor()
1154      'red'
1155      >>> turtle.pencolor("brown")
1156      >>> turtle.pencolor()
1157      'brown'
1158      >>> tup = (0.2, 0.8, 0.55)
1159      >>> turtle.pencolor(tup)
1160      >>> turtle.pencolor()
1161      (0.2, 0.8, 0.5490196078431373)
1162      >>> colormode(255)
1163      >>> turtle.pencolor()
1164      (51.0, 204.0, 140.0)
1165      >>> turtle.pencolor('#32c18f')
1166      >>> turtle.pencolor()
1167      (50.0, 193.0, 143.0)
1168
1169
1170.. function:: fillcolor(*args)
1171
1172   Return or set the fillcolor.
1173
1174   Four input formats are allowed:
1175
1176   ``fillcolor()``
1177      Return the current fillcolor as color specification string, possibly
1178      in tuple format (see example).  May be used as input to another
1179      color/pencolor/fillcolor call.
1180
1181   ``fillcolor(colorstring)``
1182      Set fillcolor to *colorstring*, which is a Tk color specification string,
1183      such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
1184
1185   ``fillcolor((r, g, b))``
1186      Set fillcolor to the RGB color represented by the tuple of *r*, *g*, and
1187      *b*.  Each of *r*, *g*, and *b* must be in the range 0..colormode, where
1188      colormode is either 1.0 or 255 (see :func:`colormode`).
1189
1190   ``fillcolor(r, g, b)``
1191      Set fillcolor to the RGB color represented by *r*, *g*, and *b*.  Each of
1192      *r*, *g*, and *b* must be in the range 0..colormode.
1193
1194   If turtleshape is a polygon, the interior of that polygon is drawn
1195   with the newly set fillcolor.
1196
1197   .. doctest::
1198      :skipif: _tkinter is None
1199
1200      >>> turtle.fillcolor("violet")
1201      >>> turtle.fillcolor()
1202      'violet'
1203      >>> turtle.pencolor()
1204      (50.0, 193.0, 143.0)
1205      >>> turtle.fillcolor((50, 193, 143))  # Integers, not floats
1206      >>> turtle.fillcolor()
1207      (50.0, 193.0, 143.0)
1208      >>> turtle.fillcolor('#ffffff')
1209      >>> turtle.fillcolor()
1210      (255.0, 255.0, 255.0)
1211
1212
1213.. function:: color(*args)
1214
1215   Return or set pencolor and fillcolor.
1216
1217   Several input formats are allowed.  They use 0 to 3 arguments as
1218   follows:
1219
1220   ``color()``
1221      Return the current pencolor and the current fillcolor as a pair of color
1222      specification strings or tuples as returned by :func:`pencolor` and
1223      :func:`fillcolor`.
1224
1225   ``color(colorstring)``, ``color((r,g,b))``, ``color(r,g,b)``
1226      Inputs as in :func:`pencolor`, set both, fillcolor and pencolor, to the
1227      given value.
1228
1229   ``color(colorstring1, colorstring2)``, ``color((r1,g1,b1), (r2,g2,b2))``
1230      Equivalent to ``pencolor(colorstring1)`` and ``fillcolor(colorstring2)``
1231      and analogously if the other input format is used.
1232
1233   If turtleshape is a polygon, outline and interior of that polygon is drawn
1234   with the newly set colors.
1235
1236   .. doctest::
1237      :skipif: _tkinter is None
1238
1239      >>> turtle.color("red", "green")
1240      >>> turtle.color()
1241      ('red', 'green')
1242      >>> color("#285078", "#a0c8f0")
1243      >>> color()
1244      ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
1245
1246
1247See also: Screen method :func:`colormode`.
1248
1249
1250Filling
1251~~~~~~~
1252
1253.. doctest::
1254   :skipif: _tkinter is None
1255   :hide:
1256
1257   >>> turtle.home()
1258
1259.. function:: filling()
1260
1261   Return fillstate (``True`` if filling, ``False`` else).
1262
1263   .. doctest::
1264      :skipif: _tkinter is None
1265
1266      >>> turtle.begin_fill()
1267      >>> if turtle.filling():
1268      ...    turtle.pensize(5)
1269      ... else:
1270      ...    turtle.pensize(3)
1271
1272
1273
1274.. function:: begin_fill()
1275
1276   To be called just before drawing a shape to be filled.
1277
1278
1279.. function:: end_fill()
1280
1281   Fill the shape drawn after the last call to :func:`begin_fill`.
1282
1283   Whether or not overlap regions for self-intersecting polygons
1284   or multiple shapes are filled depends on the operating system graphics,
1285   type of overlap, and number of overlaps.  For example, the Turtle star
1286   above may be either all yellow or have some white regions.
1287
1288   .. doctest::
1289      :skipif: _tkinter is None
1290
1291      >>> turtle.color("black", "red")
1292      >>> turtle.begin_fill()
1293      >>> turtle.circle(80)
1294      >>> turtle.end_fill()
1295
1296
1297More drawing control
1298~~~~~~~~~~~~~~~~~~~~
1299
1300.. function:: reset()
1301
1302   Delete the turtle's drawings from the screen, re-center the turtle and set
1303   variables to the default values.
1304
1305   .. doctest::
1306      :skipif: _tkinter is None
1307
1308      >>> turtle.goto(0,-22)
1309      >>> turtle.left(100)
1310      >>> turtle.position()
1311      (0.00,-22.00)
1312      >>> turtle.heading()
1313      100.0
1314      >>> turtle.reset()
1315      >>> turtle.position()
1316      (0.00,0.00)
1317      >>> turtle.heading()
1318      0.0
1319
1320
1321.. function:: clear()
1322
1323   Delete the turtle's drawings from the screen.  Do not move turtle.  State and
1324   position of the turtle as well as drawings of other turtles are not affected.
1325
1326
1327.. function:: write(arg, move=False, align="left", font=("Arial", 8, "normal"))
1328
1329   :param arg: object to be written to the TurtleScreen
1330   :param move: True/False
1331   :param align: one of the strings "left", "center" or right"
1332   :param font: a triple (fontname, fontsize, fonttype)
1333
1334   Write text - the string representation of *arg* - at the current turtle
1335   position according to *align* ("left", "center" or "right") and with the given
1336   font.  If *move* is true, the pen is moved to the bottom-right corner of the
1337   text.  By default, *move* is ``False``.
1338
1339   >>> turtle.write("Home = ", True, align="center")
1340   >>> turtle.write((0,0), True)
1341
1342
1343Turtle state
1344------------
1345
1346Visibility
1347~~~~~~~~~~
1348
1349.. function:: hideturtle()
1350              ht()
1351
1352   Make the turtle invisible.  It's a good idea to do this while you're in the
1353   middle of doing some complex drawing, because hiding the turtle speeds up the
1354   drawing observably.
1355
1356   .. doctest::
1357      :skipif: _tkinter is None
1358
1359      >>> turtle.hideturtle()
1360
1361
1362.. function:: showturtle()
1363              st()
1364
1365   Make the turtle visible.
1366
1367   .. doctest::
1368      :skipif: _tkinter is None
1369
1370      >>> turtle.showturtle()
1371
1372
1373.. function:: isvisible()
1374
1375   Return ``True`` if the Turtle is shown, ``False`` if it's hidden.
1376
1377   >>> turtle.hideturtle()
1378   >>> turtle.isvisible()
1379   False
1380   >>> turtle.showturtle()
1381   >>> turtle.isvisible()
1382   True
1383
1384
1385Appearance
1386~~~~~~~~~~
1387
1388.. function:: shape(name=None)
1389
1390   :param name: a string which is a valid shapename
1391
1392   Set turtle shape to shape with given *name* or, if name is not given, return
1393   name of current shape.  Shape with *name* must exist in the TurtleScreen's
1394   shape dictionary.  Initially there are the following polygon shapes: "arrow",
1395   "turtle", "circle", "square", "triangle", "classic".  To learn about how to
1396   deal with shapes see Screen method :func:`register_shape`.
1397
1398   .. doctest::
1399      :skipif: _tkinter is None
1400
1401      >>> turtle.shape()
1402      'classic'
1403      >>> turtle.shape("turtle")
1404      >>> turtle.shape()
1405      'turtle'
1406
1407
1408.. function:: resizemode(rmode=None)
1409
1410   :param rmode: one of the strings "auto", "user", "noresize"
1411
1412   Set resizemode to one of the values: "auto", "user", "noresize".  If *rmode*
1413   is not given, return current resizemode.  Different resizemodes have the
1414   following effects:
1415
1416   - "auto": adapts the appearance of the turtle corresponding to the value of pensize.
1417   - "user": adapts the appearance of the turtle according to the values of
1418     stretchfactor and outlinewidth (outline), which are set by
1419     :func:`shapesize`.
1420   - "noresize": no adaption of the turtle's appearance takes place.
1421
1422   ``resizemode("user")`` is called by :func:`shapesize` when used with arguments.
1423
1424   .. doctest::
1425      :skipif: _tkinter is None
1426
1427      >>> turtle.resizemode()
1428      'noresize'
1429      >>> turtle.resizemode("auto")
1430      >>> turtle.resizemode()
1431      'auto'
1432
1433
1434.. function:: shapesize(stretch_wid=None, stretch_len=None, outline=None)
1435              turtlesize(stretch_wid=None, stretch_len=None, outline=None)
1436
1437   :param stretch_wid: positive number
1438   :param stretch_len: positive number
1439   :param outline: positive number
1440
1441   Return or set the pen's attributes x/y-stretchfactors and/or outline.  Set
1442   resizemode to "user".  If and only if resizemode is set to "user", the turtle
1443   will be displayed stretched according to its stretchfactors: *stretch_wid* is
1444   stretchfactor perpendicular to its orientation, *stretch_len* is
1445   stretchfactor in direction of its orientation, *outline* determines the width
1446   of the shape's outline.
1447
1448   .. doctest::
1449      :skipif: _tkinter is None
1450
1451      >>> turtle.shapesize()
1452      (1.0, 1.0, 1)
1453      >>> turtle.resizemode("user")
1454      >>> turtle.shapesize(5, 5, 12)
1455      >>> turtle.shapesize()
1456      (5, 5, 12)
1457      >>> turtle.shapesize(outline=8)
1458      >>> turtle.shapesize()
1459      (5, 5, 8)
1460
1461
1462.. function:: shearfactor(shear=None)
1463
1464   :param shear: number (optional)
1465
1466   Set or return the current shearfactor. Shear the turtleshape according to
1467   the given shearfactor shear, which is the tangent of the shear angle.
1468   Do *not* change the turtle's heading (direction of movement).
1469   If shear is not given: return the current shearfactor, i. e. the
1470   tangent of the shear angle, by which lines parallel to the
1471   heading of the turtle are sheared.
1472
1473   .. doctest::
1474      :skipif: _tkinter is None
1475
1476      >>> turtle.shape("circle")
1477      >>> turtle.shapesize(5,2)
1478      >>> turtle.shearfactor(0.5)
1479      >>> turtle.shearfactor()
1480      0.5
1481
1482
1483.. function:: tilt(angle)
1484
1485   :param angle: a number
1486
1487   Rotate the turtleshape by *angle* from its current tilt-angle, but do *not*
1488   change the turtle's heading (direction of movement).
1489
1490   .. doctest::
1491      :skipif: _tkinter is None
1492
1493      >>> turtle.reset()
1494      >>> turtle.shape("circle")
1495      >>> turtle.shapesize(5,2)
1496      >>> turtle.tilt(30)
1497      >>> turtle.fd(50)
1498      >>> turtle.tilt(30)
1499      >>> turtle.fd(50)
1500
1501
1502.. function:: tiltangle(angle=None)
1503
1504   :param angle: a number (optional)
1505
1506   Set or return the current tilt-angle. If angle is given, rotate the
1507   turtleshape to point in the direction specified by angle,
1508   regardless of its current tilt-angle. Do *not* change the turtle's
1509   heading (direction of movement).
1510   If angle is not given: return the current tilt-angle, i. e. the angle
1511   between the orientation of the turtleshape and the heading of the
1512   turtle (its direction of movement).
1513
1514   .. doctest::
1515      :skipif: _tkinter is None
1516
1517      >>> turtle.reset()
1518      >>> turtle.shape("circle")
1519      >>> turtle.shapesize(5,2)
1520      >>> turtle.tilt(45)
1521      >>> turtle.tiltangle()
1522      45.0
1523
1524
1525.. function:: shapetransform(t11=None, t12=None, t21=None, t22=None)
1526
1527   :param t11: a number (optional)
1528   :param t12: a number (optional)
1529   :param t21: a number (optional)
1530   :param t12: a number (optional)
1531
1532   Set or return the current transformation matrix of the turtle shape.
1533
1534   If none of the matrix elements are given, return the transformation
1535   matrix as a tuple of 4 elements.
1536   Otherwise set the given elements and transform the turtleshape
1537   according to the matrix consisting of first row t11, t12 and
1538   second row t21, t22. The determinant t11 * t22 - t12 * t21 must not be
1539   zero, otherwise an error is raised.
1540   Modify stretchfactor, shearfactor and tiltangle according to the
1541   given matrix.
1542
1543   .. doctest::
1544      :skipif: _tkinter is None
1545
1546      >>> turtle = Turtle()
1547      >>> turtle.shape("square")
1548      >>> turtle.shapesize(4,2)
1549      >>> turtle.shearfactor(-0.5)
1550      >>> turtle.shapetransform()
1551      (4.0, -1.0, -0.0, 2.0)
1552
1553
1554.. function:: get_shapepoly()
1555
1556   Return the current shape polygon as tuple of coordinate pairs. This
1557   can be used to define a new shape or components of a compound shape.
1558
1559   .. doctest::
1560      :skipif: _tkinter is None
1561
1562      >>> turtle.shape("square")
1563      >>> turtle.shapetransform(4, -1, 0, 2)
1564      >>> turtle.get_shapepoly()
1565      ((50, -20), (30, 20), (-50, 20), (-30, -20))
1566
1567
1568Using events
1569------------
1570
1571.. function:: onclick(fun, btn=1, add=None)
1572   :noindex:
1573
1574   :param fun: a function with two arguments which will be called with the
1575               coordinates of the clicked point on the canvas
1576   :param btn: number of the mouse-button, defaults to 1 (left mouse button)
1577   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1578               added, otherwise it will replace a former binding
1579
1580   Bind *fun* to mouse-click events on this turtle.  If *fun* is ``None``,
1581   existing bindings are removed.  Example for the anonymous turtle, i.e. the
1582   procedural way:
1583
1584   .. doctest::
1585      :skipif: _tkinter is None
1586
1587      >>> def turn(x, y):
1588      ...     left(180)
1589      ...
1590      >>> onclick(turn)  # Now clicking into the turtle will turn it.
1591      >>> onclick(None)  # event-binding will be removed
1592
1593
1594.. function:: onrelease(fun, btn=1, add=None)
1595
1596   :param fun: a function with two arguments which will be called with the
1597               coordinates of the clicked point on the canvas
1598   :param btn: number of the mouse-button, defaults to 1 (left mouse button)
1599   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1600               added, otherwise it will replace a former binding
1601
1602   Bind *fun* to mouse-button-release events on this turtle.  If *fun* is
1603   ``None``, existing bindings are removed.
1604
1605   .. doctest::
1606      :skipif: _tkinter is None
1607
1608      >>> class MyTurtle(Turtle):
1609      ...     def glow(self,x,y):
1610      ...         self.fillcolor("red")
1611      ...     def unglow(self,x,y):
1612      ...         self.fillcolor("")
1613      ...
1614      >>> turtle = MyTurtle()
1615      >>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
1616      >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
1617
1618
1619.. function:: ondrag(fun, btn=1, add=None)
1620
1621   :param fun: a function with two arguments which will be called with the
1622               coordinates of the clicked point on the canvas
1623   :param btn: number of the mouse-button, defaults to 1 (left mouse button)
1624   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1625               added, otherwise it will replace a former binding
1626
1627   Bind *fun* to mouse-move events on this turtle.  If *fun* is ``None``,
1628   existing bindings are removed.
1629
1630   Remark: Every sequence of mouse-move-events on a turtle is preceded by a
1631   mouse-click event on that turtle.
1632
1633   .. doctest::
1634      :skipif: _tkinter is None
1635
1636      >>> turtle.ondrag(turtle.goto)
1637
1638   Subsequently, clicking and dragging the Turtle will move it across
1639   the screen thereby producing handdrawings (if pen is down).
1640
1641
1642Special Turtle methods
1643----------------------
1644
1645.. function:: begin_poly()
1646
1647   Start recording the vertices of a polygon.  Current turtle position is first
1648   vertex of polygon.
1649
1650
1651.. function:: end_poly()
1652
1653   Stop recording the vertices of a polygon.  Current turtle position is last
1654   vertex of polygon.  This will be connected with the first vertex.
1655
1656
1657.. function:: get_poly()
1658
1659   Return the last recorded polygon.
1660
1661   .. doctest::
1662      :skipif: _tkinter is None
1663
1664      >>> turtle.home()
1665      >>> turtle.begin_poly()
1666      >>> turtle.fd(100)
1667      >>> turtle.left(20)
1668      >>> turtle.fd(30)
1669      >>> turtle.left(60)
1670      >>> turtle.fd(50)
1671      >>> turtle.end_poly()
1672      >>> p = turtle.get_poly()
1673      >>> register_shape("myFavouriteShape", p)
1674
1675
1676.. function:: clone()
1677
1678   Create and return a clone of the turtle with same position, heading and
1679   turtle properties.
1680
1681   .. doctest::
1682      :skipif: _tkinter is None
1683
1684      >>> mick = Turtle()
1685      >>> joe = mick.clone()
1686
1687
1688.. function:: getturtle()
1689              getpen()
1690
1691   Return the Turtle object itself.  Only reasonable use: as a function to
1692   return the "anonymous turtle":
1693
1694   .. doctest::
1695      :skipif: _tkinter is None
1696
1697      >>> pet = getturtle()
1698      >>> pet.fd(50)
1699      >>> pet
1700      <turtle.Turtle object at 0x...>
1701
1702
1703.. function:: getscreen()
1704
1705   Return the :class:`TurtleScreen` object the turtle is drawing on.
1706   TurtleScreen methods can then be called for that object.
1707
1708   .. doctest::
1709      :skipif: _tkinter is None
1710
1711      >>> ts = turtle.getscreen()
1712      >>> ts
1713      <turtle._Screen object at 0x...>
1714      >>> ts.bgcolor("pink")
1715
1716
1717.. function:: setundobuffer(size)
1718
1719   :param size: an integer or ``None``
1720
1721   Set or disable undobuffer.  If *size* is an integer, an empty undobuffer of
1722   given size is installed.  *size* gives the maximum number of turtle actions
1723   that can be undone by the :func:`undo` method/function.  If *size* is
1724   ``None``, the undobuffer is disabled.
1725
1726   .. doctest::
1727      :skipif: _tkinter is None
1728
1729      >>> turtle.setundobuffer(42)
1730
1731
1732.. function:: undobufferentries()
1733
1734   Return number of entries in the undobuffer.
1735
1736   .. doctest::
1737      :skipif: _tkinter is None
1738
1739      >>> while undobufferentries():
1740      ...     undo()
1741
1742
1743
1744.. _compoundshapes:
1745
1746Compound shapes
1747---------------
1748
1749To use compound turtle shapes, which consist of several polygons of different
1750color, you must use the helper class :class:`Shape` explicitly as described
1751below:
1752
17531. Create an empty Shape object of type "compound".
17542. Add as many components to this object as desired, using the
1755   :meth:`~Shape.addcomponent` method.
1756
1757   For example:
1758
1759   .. doctest::
1760      :skipif: _tkinter is None
1761
1762      >>> s = Shape("compound")
1763      >>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
1764      >>> s.addcomponent(poly1, "red", "blue")
1765      >>> poly2 = ((0,0),(10,-5),(-10,-5))
1766      >>> s.addcomponent(poly2, "blue", "red")
1767
17683. Now add the Shape to the Screen's shapelist and use it:
1769
1770   .. doctest::
1771      :skipif: _tkinter is None
1772
1773      >>> register_shape("myshape", s)
1774      >>> shape("myshape")
1775
1776
1777.. note::
1778
1779   The :class:`Shape` class is used internally by the :func:`register_shape`
1780   method in different ways.  The application programmer has to deal with the
1781   Shape class *only* when using compound shapes like shown above!
1782
1783
1784Methods of TurtleScreen/Screen and corresponding functions
1785==========================================================
1786
1787Most of the examples in this section refer to a TurtleScreen instance called
1788``screen``.
1789
1790.. doctest::
1791   :skipif: _tkinter is None
1792   :hide:
1793
1794   >>> screen = Screen()
1795
1796Window control
1797--------------
1798
1799.. function:: bgcolor(*args)
1800
1801   :param args: a color string or three numbers in the range 0..colormode or a
1802                3-tuple of such numbers
1803
1804
1805   Set or return background color of the TurtleScreen.
1806
1807   .. doctest::
1808      :skipif: _tkinter is None
1809
1810      >>> screen.bgcolor("orange")
1811      >>> screen.bgcolor()
1812      'orange'
1813      >>> screen.bgcolor("#800080")
1814      >>> screen.bgcolor()
1815      (128.0, 0.0, 128.0)
1816
1817
1818.. function:: bgpic(picname=None)
1819
1820   :param picname: a string, name of a gif-file or ``"nopic"``, or ``None``
1821
1822   Set background image or return name of current backgroundimage.  If *picname*
1823   is a filename, set the corresponding image as background.  If *picname* is
1824   ``"nopic"``, delete background image, if present.  If *picname* is ``None``,
1825   return the filename of the current backgroundimage. ::
1826
1827      >>> screen.bgpic()
1828      'nopic'
1829      >>> screen.bgpic("landscape.gif")
1830      >>> screen.bgpic()
1831      "landscape.gif"
1832
1833
1834.. function:: clear()
1835   :noindex:
1836
1837   .. note::
1838      This TurtleScreen method is available as a global function only under the
1839      name ``clearscreen``.  The global function ``clear`` is a different one
1840      derived from the Turtle method ``clear``.
1841
1842
1843.. function:: clearscreen()
1844
1845   Delete all drawings and all turtles from the TurtleScreen.  Reset the now
1846   empty TurtleScreen to its initial state: white background, no background
1847   image, no event bindings and tracing on.
1848
1849
1850.. function:: reset()
1851   :noindex:
1852
1853   .. note::
1854      This TurtleScreen method is available as a global function only under the
1855      name ``resetscreen``.  The global function ``reset`` is another one
1856      derived from the Turtle method ``reset``.
1857
1858
1859.. function:: resetscreen()
1860
1861   Reset all Turtles on the Screen to their initial state.
1862
1863
1864.. function:: screensize(canvwidth=None, canvheight=None, bg=None)
1865
1866   :param canvwidth: positive integer, new width of canvas in pixels
1867   :param canvheight: positive integer, new height of canvas in pixels
1868   :param bg: colorstring or color-tuple, new background color
1869
1870   If no arguments are given, return current (canvaswidth, canvasheight).  Else
1871   resize the canvas the turtles are drawing on.  Do not alter the drawing
1872   window.  To observe hidden parts of the canvas, use the scrollbars. With this
1873   method, one can make visible those parts of a drawing which were outside the
1874   canvas before.
1875
1876      >>> screen.screensize()
1877      (400, 300)
1878      >>> screen.screensize(2000,1500)
1879      >>> screen.screensize()
1880      (2000, 1500)
1881
1882   e.g. to search for an erroneously escaped turtle ;-)
1883
1884
1885.. function:: setworldcoordinates(llx, lly, urx, ury)
1886
1887   :param llx: a number, x-coordinate of lower left corner of canvas
1888   :param lly: a number, y-coordinate of lower left corner of canvas
1889   :param urx: a number, x-coordinate of upper right corner of canvas
1890   :param ury: a number, y-coordinate of upper right corner of canvas
1891
1892   Set up user-defined coordinate system and switch to mode "world" if
1893   necessary.  This performs a ``screen.reset()``.  If mode "world" is already
1894   active, all drawings are redrawn according to the new coordinates.
1895
1896   **ATTENTION**: in user-defined coordinate systems angles may appear
1897   distorted.
1898
1899   .. doctest::
1900      :skipif: _tkinter is None
1901
1902      >>> screen.reset()
1903      >>> screen.setworldcoordinates(-50,-7.5,50,7.5)
1904      >>> for _ in range(72):
1905      ...     left(10)
1906      ...
1907      >>> for _ in range(8):
1908      ...     left(45); fd(2)   # a regular octagon
1909
1910   .. doctest::
1911      :skipif: _tkinter is None
1912      :hide:
1913
1914      >>> screen.reset()
1915      >>> for t in turtles():
1916      ...      t.reset()
1917
1918
1919Animation control
1920-----------------
1921
1922.. function:: delay(delay=None)
1923
1924   :param delay: positive integer
1925
1926   Set or return the drawing *delay* in milliseconds.  (This is approximately
1927   the time interval between two consecutive canvas updates.)  The longer the
1928   drawing delay, the slower the animation.
1929
1930   Optional argument:
1931
1932   .. doctest::
1933      :skipif: _tkinter is None
1934
1935      >>> screen.delay()
1936      10
1937      >>> screen.delay(5)
1938      >>> screen.delay()
1939      5
1940
1941
1942.. function:: tracer(n=None, delay=None)
1943
1944   :param n: nonnegative integer
1945   :param delay: nonnegative integer
1946
1947   Turn turtle animation on/off and set delay for update drawings.  If
1948   *n* is given, only each n-th regular screen update is really
1949   performed.  (Can be used to accelerate the drawing of complex
1950   graphics.)  When called without arguments, returns the currently
1951   stored value of n. Second argument sets delay value (see
1952   :func:`delay`).
1953
1954   .. doctest::
1955      :skipif: _tkinter is None
1956
1957      >>> screen.tracer(8, 25)
1958      >>> dist = 2
1959      >>> for i in range(200):
1960      ...     fd(dist)
1961      ...     rt(90)
1962      ...     dist += 2
1963
1964
1965.. function:: update()
1966
1967   Perform a TurtleScreen update. To be used when tracer is turned off.
1968
1969See also the RawTurtle/Turtle method :func:`speed`.
1970
1971
1972Using screen events
1973-------------------
1974
1975.. function:: listen(xdummy=None, ydummy=None)
1976
1977   Set focus on TurtleScreen (in order to collect key-events).  Dummy arguments
1978   are provided in order to be able to pass :func:`listen` to the onclick method.
1979
1980
1981.. function:: onkey(fun, key)
1982              onkeyrelease(fun, key)
1983
1984   :param fun: a function with no arguments or ``None``
1985   :param key: a string: key (e.g. "a") or key-symbol (e.g. "space")
1986
1987   Bind *fun* to key-release event of key.  If *fun* is ``None``, event bindings
1988   are removed. Remark: in order to be able to register key-events, TurtleScreen
1989   must have the focus. (See method :func:`listen`.)
1990
1991   .. doctest::
1992      :skipif: _tkinter is None
1993
1994      >>> def f():
1995      ...     fd(50)
1996      ...     lt(60)
1997      ...
1998      >>> screen.onkey(f, "Up")
1999      >>> screen.listen()
2000
2001
2002.. function:: onkeypress(fun, key=None)
2003
2004   :param fun: a function with no arguments or ``None``
2005   :param key: a string: key (e.g. "a") or key-symbol (e.g. "space")
2006
2007   Bind *fun* to key-press event of key if key is given,
2008   or to any key-press-event if no key is given.
2009   Remark: in order to be able to register key-events, TurtleScreen
2010   must have focus. (See method :func:`listen`.)
2011
2012   .. doctest::
2013      :skipif: _tkinter is None
2014
2015      >>> def f():
2016      ...     fd(50)
2017      ...
2018      >>> screen.onkey(f, "Up")
2019      >>> screen.listen()
2020
2021
2022.. function:: onclick(fun, btn=1, add=None)
2023              onscreenclick(fun, btn=1, add=None)
2024
2025   :param fun: a function with two arguments which will be called with the
2026               coordinates of the clicked point on the canvas
2027   :param btn: number of the mouse-button, defaults to 1 (left mouse button)
2028   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
2029               added, otherwise it will replace a former binding
2030
2031   Bind *fun* to mouse-click events on this screen.  If *fun* is ``None``,
2032   existing bindings are removed.
2033
2034   Example for a TurtleScreen instance named ``screen`` and a Turtle instance
2035   named ``turtle``:
2036
2037   .. doctest::
2038      :skipif: _tkinter is None
2039
2040      >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
2041      >>>                             # make the turtle move to the clicked point.
2042      >>> screen.onclick(None)        # remove event binding again
2043
2044   .. note::
2045      This TurtleScreen method is available as a global function only under the
2046      name ``onscreenclick``.  The global function ``onclick`` is another one
2047      derived from the Turtle method ``onclick``.
2048
2049
2050.. function:: ontimer(fun, t=0)
2051
2052   :param fun: a function with no arguments
2053   :param t: a number >= 0
2054
2055   Install a timer that calls *fun* after *t* milliseconds.
2056
2057   .. doctest::
2058      :skipif: _tkinter is None
2059
2060      >>> running = True
2061      >>> def f():
2062      ...     if running:
2063      ...         fd(50)
2064      ...         lt(60)
2065      ...         screen.ontimer(f, 250)
2066      >>> f()   ### makes the turtle march around
2067      >>> running = False
2068
2069
2070.. function:: mainloop()
2071              done()
2072
2073   Starts event loop - calling Tkinter's mainloop function.
2074   Must be the last statement in a turtle graphics program.
2075   Must *not* be used if a script is run from within IDLE in -n mode
2076   (No subprocess) - for interactive use of turtle graphics. ::
2077
2078      >>> screen.mainloop()
2079
2080
2081Input methods
2082-------------
2083
2084.. function:: textinput(title, prompt)
2085
2086   :param title: string
2087   :param prompt: string
2088
2089   Pop up a dialog window for input of a string. Parameter title is
2090   the title of the dialog window, prompt is a text mostly describing
2091   what information to input.
2092   Return the string input. If the dialog is canceled, return ``None``. ::
2093
2094      >>> screen.textinput("NIM", "Name of first player:")
2095
2096
2097.. function:: numinput(title, prompt, default=None, minval=None, maxval=None)
2098
2099   :param title: string
2100   :param prompt: string
2101   :param default: number (optional)
2102   :param minval: number (optional)
2103   :param maxval: number (optional)
2104
2105   Pop up a dialog window for input of a number. title is the title of the
2106   dialog window, prompt is a text mostly describing what numerical information
2107   to input. default: default value, minval: minimum value for input,
2108   maxval: maximum value for input.
2109   The number input must be in the range minval .. maxval if these are
2110   given. If not, a hint is issued and the dialog remains open for
2111   correction.
2112   Return the number input. If the dialog is canceled,  return ``None``. ::
2113
2114      >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
2115
2116
2117Settings and special methods
2118----------------------------
2119
2120.. function:: mode(mode=None)
2121
2122   :param mode: one of the strings "standard", "logo" or "world"
2123
2124   Set turtle mode ("standard", "logo" or "world") and perform reset.  If mode
2125   is not given, current mode is returned.
2126
2127   Mode "standard" is compatible with old :mod:`turtle`.  Mode "logo" is
2128   compatible with most Logo turtle graphics.  Mode "world" uses user-defined
2129   "world coordinates". **Attention**: in this mode angles appear distorted if
2130   ``x/y`` unit-ratio doesn't equal 1.
2131
2132   ============ ========================= ===================
2133       Mode      Initial turtle heading     positive angles
2134   ============ ========================= ===================
2135    "standard"    to the right (east)       counterclockwise
2136      "logo"        upward    (north)         clockwise
2137   ============ ========================= ===================
2138
2139   .. doctest::
2140      :skipif: _tkinter is None
2141
2142      >>> mode("logo")   # resets turtle heading to north
2143      >>> mode()
2144      'logo'
2145
2146
2147.. function:: colormode(cmode=None)
2148
2149   :param cmode: one of the values 1.0 or 255
2150
2151   Return the colormode or set it to 1.0 or 255.  Subsequently *r*, *g*, *b*
2152   values of color triples have to be in the range 0..*cmode*.
2153
2154   .. doctest::
2155      :skipif: _tkinter is None
2156
2157      >>> screen.colormode(1)
2158      >>> turtle.pencolor(240, 160, 80)
2159      Traceback (most recent call last):
2160           ...
2161      TurtleGraphicsError: bad color sequence: (240, 160, 80)
2162      >>> screen.colormode()
2163      1.0
2164      >>> screen.colormode(255)
2165      >>> screen.colormode()
2166      255
2167      >>> turtle.pencolor(240,160,80)
2168
2169
2170.. function:: getcanvas()
2171
2172   Return the Canvas of this TurtleScreen.  Useful for insiders who know what to
2173   do with a Tkinter Canvas.
2174
2175   .. doctest::
2176      :skipif: _tkinter is None
2177
2178      >>> cv = screen.getcanvas()
2179      >>> cv
2180      <turtle.ScrolledCanvas object ...>
2181
2182
2183.. function:: getshapes()
2184
2185   Return a list of names of all currently available turtle shapes.
2186
2187   .. doctest::
2188      :skipif: _tkinter is None
2189
2190      >>> screen.getshapes()
2191      ['arrow', 'blank', 'circle', ..., 'turtle']
2192
2193
2194.. function:: register_shape(name, shape=None)
2195              addshape(name, shape=None)
2196
2197   There are three different ways to call this function:
2198
2199   (1) *name* is the name of a gif-file and *shape* is ``None``: Install the
2200       corresponding image shape. ::
2201
2202       >>> screen.register_shape("turtle.gif")
2203
2204       .. note::
2205          Image shapes *do not* rotate when turning the turtle, so they do not
2206          display the heading of the turtle!
2207
2208   (2) *name* is an arbitrary string and *shape* is a tuple of pairs of
2209       coordinates: Install the corresponding polygon shape.
2210
2211       .. doctest::
2212          :skipif: _tkinter is None
2213
2214          >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
2215
2216   (3) *name* is an arbitrary string and *shape* is a (compound) :class:`Shape`
2217       object: Install the corresponding compound shape.
2218
2219   Add a turtle shape to TurtleScreen's shapelist.  Only thusly registered
2220   shapes can be used by issuing the command ``shape(shapename)``.
2221
2222
2223.. function:: turtles()
2224
2225   Return the list of turtles on the screen.
2226
2227   .. doctest::
2228      :skipif: _tkinter is None
2229
2230      >>> for turtle in screen.turtles():
2231      ...     turtle.color("red")
2232
2233
2234.. function:: window_height()
2235
2236   Return the height of the turtle window. ::
2237
2238      >>> screen.window_height()
2239      480
2240
2241
2242.. function:: window_width()
2243
2244   Return the width of the turtle window. ::
2245
2246      >>> screen.window_width()
2247      640
2248
2249
2250.. _screenspecific:
2251
2252Methods specific to Screen, not inherited from TurtleScreen
2253-----------------------------------------------------------
2254
2255.. function:: bye()
2256
2257   Shut the turtlegraphics window.
2258
2259
2260.. function:: exitonclick()
2261
2262   Bind ``bye()`` method to mouse clicks on the Screen.
2263
2264
2265   If the value "using_IDLE" in the configuration dictionary is ``False``
2266   (default value), also enter mainloop.  Remark: If IDLE with the ``-n`` switch
2267   (no subprocess) is used, this value should be set to ``True`` in
2268   :file:`turtle.cfg`.  In this case IDLE's own mainloop is active also for the
2269   client script.
2270
2271
2272.. function:: setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])
2273
2274   Set the size and position of the main window.  Default values of arguments
2275   are stored in the configuration dictionary and can be changed via a
2276   :file:`turtle.cfg` file.
2277
2278   :param width: if an integer, a size in pixels, if a float, a fraction of the
2279                 screen; default is 50% of screen
2280   :param height: if an integer, the height in pixels, if a float, a fraction of
2281                  the screen; default is 75% of screen
2282   :param startx: if positive, starting position in pixels from the left
2283                  edge of the screen, if negative from the right edge, if ``None``,
2284                  center window horizontally
2285   :param starty: if positive, starting position in pixels from the top
2286                  edge of the screen, if negative from the bottom edge, if ``None``,
2287                  center window vertically
2288
2289   .. doctest::
2290      :skipif: _tkinter is None
2291
2292      >>> screen.setup (width=200, height=200, startx=0, starty=0)
2293      >>>              # sets window to 200x200 pixels, in upper left of screen
2294      >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
2295      >>>              # sets window to 75% of screen by 50% of screen and centers
2296
2297
2298.. function:: title(titlestring)
2299
2300   :param titlestring: a string that is shown in the titlebar of the turtle
2301                       graphics window
2302
2303   Set title of turtle window to *titlestring*.
2304
2305   .. doctest::
2306      :skipif: _tkinter is None
2307
2308      >>> screen.title("Welcome to the turtle zoo!")
2309
2310
2311Public classes
2312==============
2313
2314
2315.. class:: RawTurtle(canvas)
2316           RawPen(canvas)
2317
2318   :param canvas: a :class:`!tkinter.Canvas`, a :class:`ScrolledCanvas` or a
2319                  :class:`TurtleScreen`
2320
2321   Create a turtle.  The turtle has all methods described above as "methods of
2322   Turtle/RawTurtle".
2323
2324
2325.. class:: Turtle()
2326
2327   Subclass of RawTurtle, has the same interface but draws on a default
2328   :class:`Screen` object created automatically when needed for the first time.
2329
2330
2331.. class:: TurtleScreen(cv)
2332
2333   :param cv: a :class:`!tkinter.Canvas`
2334
2335   Provides screen oriented methods like :func:`bgcolor` etc. that are described
2336   above.
2337
2338.. class:: Screen()
2339
2340   Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`.
2341
2342
2343.. class:: ScrolledCanvas(master)
2344
2345   :param master: some Tkinter widget to contain the ScrolledCanvas, i.e.
2346      a Tkinter-canvas with scrollbars added
2347
2348   Used by class Screen, which thus automatically provides a ScrolledCanvas as
2349   playground for the turtles.
2350
2351.. class:: Shape(type_, data)
2352
2353   :param type\_: one of the strings "polygon", "image", "compound"
2354
2355   Data structure modeling shapes.  The pair ``(type_, data)`` must follow this
2356   specification:
2357
2358
2359   =========== ===========
2360   *type_*     *data*
2361   =========== ===========
2362   "polygon"   a polygon-tuple, i.e. a tuple of pairs of coordinates
2363   "image"     an image  (in this form only used internally!)
2364   "compound"  ``None`` (a compound shape has to be constructed using the
2365               :meth:`addcomponent` method)
2366   =========== ===========
2367
2368   .. method:: addcomponent(poly, fill, outline=None)
2369
2370      :param poly: a polygon, i.e. a tuple of pairs of numbers
2371      :param fill: a color the *poly* will be filled with
2372      :param outline: a color for the poly's outline (if given)
2373
2374      Example:
2375
2376      .. doctest::
2377         :skipif: _tkinter is None
2378
2379         >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
2380         >>> s = Shape("compound")
2381         >>> s.addcomponent(poly, "red", "blue")
2382         >>> # ... add more components and then use register_shape()
2383
2384      See :ref:`compoundshapes`.
2385
2386
2387.. class:: Vec2D(x, y)
2388
2389   A two-dimensional vector class, used as a helper class for implementing
2390   turtle graphics.  May be useful for turtle graphics programs too.  Derived
2391   from tuple, so a vector is a tuple!
2392
2393   Provides (for *a*, *b* vectors, *k* number):
2394
2395   * ``a + b`` vector addition
2396   * ``a - b`` vector subtraction
2397   * ``a * b`` inner product
2398   * ``k * a`` and ``a * k`` multiplication with scalar
2399   * ``abs(a)`` absolute value of a
2400   * ``a.rotate(angle)`` rotation
2401
2402
2403.. _turtle-explanation:
2404
2405Explanation
2406===========
2407
2408A turtle object draws on a screen object, and there a number of key classes in
2409the turtle object-oriented interface that can be used to create them and relate
2410them to each other.
2411
2412A :class:`Turtle` instance will automatically create a :class:`Screen`
2413instance if one is not already present.
2414
2415``Turtle`` is a subclass of :class:`RawTurtle`, which *doesn't* automatically
2416create a drawing surface - a *canvas* will need to be provided or created for
2417it. The *canvas* can be a :class:`!tkinter.Canvas`, :class:`ScrolledCanvas`
2418or :class:`TurtleScreen`.
2419
2420
2421:class:`TurtleScreen` is the basic drawing surface for a
2422turtle. :class:`Screen` is a subclass of ``TurtleScreen``, and
2423includes :ref:`some additional methods <screenspecific>` for managing its
2424appearance (including size and title) and behaviour. ``TurtleScreen``'s
2425constructor needs a :class:`!tkinter.Canvas` or a
2426:class:`ScrolledCanvas` as an argument.
2427
2428The functional interface for turtle graphics uses the various methods of
2429``Turtle`` and ``TurtleScreen``/``Screen``. Behind the scenes, a screen
2430object is automatically created whenever a function derived from a ``Screen``
2431method is called. Similarly, a turtle object is automatically created
2432whenever any of the functions derived from a Turtle method is called.
2433
2434To use multiple turtles on a screen, the object-oriented interface must be
2435used.
2436
2437
2438Help and configuration
2439======================
2440
2441How to use help
2442---------------
2443
2444The public methods of the Screen and Turtle classes are documented extensively
2445via docstrings.  So these can be used as online-help via the Python help
2446facilities:
2447
2448- When using IDLE, tooltips show the signatures and first lines of the
2449  docstrings of typed in function-/method calls.
2450
2451- Calling :func:`help` on methods or functions displays the docstrings::
2452
2453     >>> help(Screen.bgcolor)
2454     Help on method bgcolor in module turtle:
2455
2456     bgcolor(self, *args) unbound turtle.Screen method
2457         Set or return backgroundcolor of the TurtleScreen.
2458
2459         Arguments (if given): a color string or three numbers
2460         in the range 0..colormode or a 3-tuple of such numbers.
2461
2462
2463         >>> screen.bgcolor("orange")
2464         >>> screen.bgcolor()
2465         "orange"
2466         >>> screen.bgcolor(0.5,0,0.5)
2467         >>> screen.bgcolor()
2468         "#800080"
2469
2470     >>> help(Turtle.penup)
2471     Help on method penup in module turtle:
2472
2473     penup(self) unbound turtle.Turtle method
2474         Pull the pen up -- no drawing when moving.
2475
2476         Aliases: penup | pu | up
2477
2478         No argument
2479
2480         >>> turtle.penup()
2481
2482- The docstrings of the functions which are derived from methods have a modified
2483  form::
2484
2485     >>> help(bgcolor)
2486     Help on function bgcolor in module turtle:
2487
2488     bgcolor(*args)
2489         Set or return backgroundcolor of the TurtleScreen.
2490
2491         Arguments (if given): a color string or three numbers
2492         in the range 0..colormode or a 3-tuple of such numbers.
2493
2494         Example::
2495
2496           >>> bgcolor("orange")
2497           >>> bgcolor()
2498           "orange"
2499           >>> bgcolor(0.5,0,0.5)
2500           >>> bgcolor()
2501           "#800080"
2502
2503     >>> help(penup)
2504     Help on function penup in module turtle:
2505
2506     penup()
2507         Pull the pen up -- no drawing when moving.
2508
2509         Aliases: penup | pu | up
2510
2511         No argument
2512
2513         Example:
2514         >>> penup()
2515
2516These modified docstrings are created automatically together with the function
2517definitions that are derived from the methods at import time.
2518
2519
2520Translation of docstrings into different languages
2521--------------------------------------------------
2522
2523There is a utility to create a dictionary the keys of which are the method names
2524and the values of which are the docstrings of the public methods of the classes
2525Screen and Turtle.
2526
2527.. function:: write_docstringdict(filename="turtle_docstringdict")
2528
2529   :param filename: a string, used as filename
2530
2531   Create and write docstring-dictionary to a Python script with the given
2532   filename.  This function has to be called explicitly (it is not used by the
2533   turtle graphics classes).  The docstring dictionary will be written to the
2534   Python script :file:`{filename}.py`.  It is intended to serve as a template
2535   for translation of the docstrings into different languages.
2536
2537If you (or your students) want to use :mod:`turtle` with online help in your
2538native language, you have to translate the docstrings and save the resulting
2539file as e.g. :file:`turtle_docstringdict_german.py`.
2540
2541If you have an appropriate entry in your :file:`turtle.cfg` file this dictionary
2542will be read in at import time and will replace the original English docstrings.
2543
2544At the time of this writing there are docstring dictionaries in German and in
2545Italian.  (Requests please to glingl@aon.at.)
2546
2547
2548
2549How to configure Screen and Turtles
2550-----------------------------------
2551
2552The built-in default configuration mimics the appearance and behaviour of the
2553old turtle module in order to retain best possible compatibility with it.
2554
2555If you want to use a different configuration which better reflects the features
2556of this module or which better fits to your needs, e.g. for use in a classroom,
2557you can prepare a configuration file ``turtle.cfg`` which will be read at import
2558time and modify the configuration according to its settings.
2559
2560The built in configuration would correspond to the following ``turtle.cfg``:
2561
2562.. code-block:: ini
2563
2564   width = 0.5
2565   height = 0.75
2566   leftright = None
2567   topbottom = None
2568   canvwidth = 400
2569   canvheight = 300
2570   mode = standard
2571   colormode = 1.0
2572   delay = 10
2573   undobuffersize = 1000
2574   shape = classic
2575   pencolor = black
2576   fillcolor = black
2577   resizemode = noresize
2578   visible = True
2579   language = english
2580   exampleturtle = turtle
2581   examplescreen = screen
2582   title = Python Turtle Graphics
2583   using_IDLE = False
2584
2585Short explanation of selected entries:
2586
2587- The first four lines correspond to the arguments of the :func:`Screen.setup <setup>`
2588  method.
2589- Line 5 and 6 correspond to the arguments of the method
2590  :func:`Screen.screensize <screensize>`.
2591- *shape* can be any of the built-in shapes, e.g: arrow, turtle, etc.  For more
2592  info try ``help(shape)``.
2593- If you want to use no fill color (i.e. make the turtle transparent), you have
2594  to write ``fillcolor = ""`` (but all nonempty strings must not have quotes in
2595  the cfg file).
2596- If you want to reflect the turtle its state, you have to use ``resizemode =
2597  auto``.
2598- If you set e.g. ``language = italian`` the docstringdict
2599  :file:`turtle_docstringdict_italian.py` will be loaded at import time (if
2600  present on the import path, e.g. in the same directory as :mod:`turtle`).
2601- The entries *exampleturtle* and *examplescreen* define the names of these
2602  objects as they occur in the docstrings.  The transformation of
2603  method-docstrings to function-docstrings will delete these names from the
2604  docstrings.
2605- *using_IDLE*: Set this to ``True`` if you regularly work with IDLE and its ``-n``
2606  switch ("no subprocess").  This will prevent :func:`exitonclick` to enter the
2607  mainloop.
2608
2609There can be a :file:`turtle.cfg` file in the directory where :mod:`turtle` is
2610stored and an additional one in the current working directory.  The latter will
2611override the settings of the first one.
2612
2613The :file:`Lib/turtledemo` directory contains a :file:`turtle.cfg` file.  You can
2614study it as an example and see its effects when running the demos (preferably
2615not from within the demo-viewer).
2616
2617
2618:mod:`turtledemo` --- Demo scripts
2619==================================
2620
2621.. module:: turtledemo
2622   :synopsis: A viewer for example turtle scripts
2623
2624The :mod:`turtledemo` package includes a set of demo scripts.  These
2625scripts can be run and viewed using the supplied demo viewer as follows::
2626
2627   python -m turtledemo
2628
2629Alternatively, you can run the demo scripts individually.  For example, ::
2630
2631   python -m turtledemo.bytedesign
2632
2633The :mod:`turtledemo` package directory contains:
2634
2635- A demo viewer :file:`__main__.py` which can be used to view the sourcecode
2636  of the scripts and run them at the same time.
2637- Multiple scripts demonstrating different features of the :mod:`turtle`
2638  module.  Examples can be accessed via the Examples menu.  They can also
2639  be run standalone.
2640- A :file:`turtle.cfg` file which serves as an example of how to write
2641  and use such files.
2642
2643The demo scripts are:
2644
2645.. currentmodule:: turtle
2646
2647.. tabularcolumns:: |l|L|L|
2648
2649+----------------+------------------------------+-----------------------+
2650| Name           | Description                  | Features              |
2651+================+==============================+=======================+
2652| bytedesign     | complex classical            | :func:`tracer`, delay,|
2653|                | turtle graphics pattern      | :func:`update`        |
2654+----------------+------------------------------+-----------------------+
2655| chaos          | graphs Verhulst dynamics,    | world coordinates     |
2656|                | shows that computer's        |                       |
2657|                | computations can generate    |                       |
2658|                | results sometimes against the|                       |
2659|                | common sense expectations    |                       |
2660+----------------+------------------------------+-----------------------+
2661| clock          | analog clock showing time    | turtles as clock's    |
2662|                | of your computer             | hands, ontimer        |
2663+----------------+------------------------------+-----------------------+
2664| colormixer     | experiment with r, g, b      | :func:`ondrag`        |
2665+----------------+------------------------------+-----------------------+
2666| forest         | 3 breadth-first trees        | randomization         |
2667+----------------+------------------------------+-----------------------+
2668| fractalcurves  | Hilbert & Koch curves        | recursion             |
2669+----------------+------------------------------+-----------------------+
2670| lindenmayer    | ethnomathematics             | L-System              |
2671|                | (indian kolams)              |                       |
2672+----------------+------------------------------+-----------------------+
2673| minimal_hanoi  | Towers of Hanoi              | Rectangular Turtles   |
2674|                |                              | as Hanoi discs        |
2675|                |                              | (shape, shapesize)    |
2676+----------------+------------------------------+-----------------------+
2677| nim            | play the classical nim game  | turtles as nimsticks, |
2678|                | with three heaps of sticks   | event driven (mouse,  |
2679|                | against the computer.        | keyboard)             |
2680+----------------+------------------------------+-----------------------+
2681| paint          | super minimalistic           | :func:`onclick`       |
2682|                | drawing program              |                       |
2683+----------------+------------------------------+-----------------------+
2684| peace          | elementary                   | turtle: appearance    |
2685|                |                              | and animation         |
2686+----------------+------------------------------+-----------------------+
2687| penrose        | aperiodic tiling with        | :func:`stamp`         |
2688|                | kites and darts              |                       |
2689+----------------+------------------------------+-----------------------+
2690| planet_and_moon| simulation of                | compound shapes,      |
2691|                | gravitational system         | :class:`Vec2D`        |
2692+----------------+------------------------------+-----------------------+
2693| rosette        | a pattern from the wikipedia | :func:`clone`,        |
2694|                | article on turtle graphics   | :func:`undo`          |
2695+----------------+------------------------------+-----------------------+
2696| round_dance    | dancing turtles rotating     | compound shapes, clone|
2697|                | pairwise in opposite         | shapesize, tilt,      |
2698|                | direction                    | get_shapepoly, update |
2699+----------------+------------------------------+-----------------------+
2700| sorting_animate| visual demonstration of      | simple alignment,     |
2701|                | different sorting methods    | randomization         |
2702+----------------+------------------------------+-----------------------+
2703| tree           | a (graphical) breadth        | :func:`clone`         |
2704|                | first tree (using generators)|                       |
2705+----------------+------------------------------+-----------------------+
2706| two_canvases   | simple design                | turtles on two        |
2707|                |                              | canvases              |
2708+----------------+------------------------------+-----------------------+
2709| yinyang        | another elementary example   | :func:`circle`        |
2710+----------------+------------------------------+-----------------------+
2711
2712Have fun!
2713
2714
2715Changes since Python 2.6
2716========================
2717
2718- The methods :func:`Turtle.tracer <tracer>`, :func:`Turtle.window_width <window_width>` and
2719  :func:`Turtle.window_height <window_height>` have been eliminated.
2720  Methods with these names and functionality are now available only
2721  as methods of :class:`Screen`. The functions derived from these remain
2722  available. (In fact already in Python 2.6 these methods were merely
2723  duplications of the corresponding
2724  :class:`TurtleScreen`/:class:`Screen` methods.)
2725
2726- The method :func:`!Turtle.fill` has been eliminated.
2727  The behaviour of :func:`begin_fill` and :func:`end_fill`
2728  have changed slightly: now every filling process must be completed with an
2729  ``end_fill()`` call.
2730
2731- A method :func:`Turtle.filling <filling>` has been added. It returns a boolean
2732  value: ``True`` if a filling process is under way, ``False`` otherwise.
2733  This behaviour corresponds to a ``fill()`` call without arguments in
2734  Python 2.6.
2735
2736Changes since Python 3.0
2737========================
2738
2739- The :class:`Turtle` methods :func:`shearfactor`, :func:`shapetransform` and
2740  :func:`get_shapepoly` have been added. Thus the full range of
2741  regular linear transforms is now available for transforming turtle shapes.
2742  :func:`tiltangle` has been enhanced in functionality: it now can
2743  be used to get or set the tilt angle.
2744
2745- The :class:`Screen` method :func:`onkeypress` has been added as a complement to
2746  :func:`onkey`. As the latter binds actions to the key release event,
2747  an alias: :func:`onkeyrelease` was also added for it.
2748
2749- The method :func:`Screen.mainloop <mainloop>` has been added,
2750  so there is no longer a need to use the standalone :func:`mainloop` function
2751  when working with :class:`Screen` and :class:`Turtle` objects.
2752
2753- Two input methods have been added: :func:`Screen.textinput <textinput>` and
2754  :func:`Screen.numinput <numinput>`. These pop up input dialogs and return
2755  strings and numbers respectively.
2756
2757- Two example scripts :file:`tdemo_nim.py` and :file:`tdemo_round_dance.py`
2758  have been added to the :file:`Lib/turtledemo` directory.
2759
2760
2761.. doctest::
2762   :skipif: _tkinter is None
2763   :hide:
2764
2765   >>> for turtle in turtles():
2766   ...      turtle.reset()
2767   >>> turtle.penup()
2768   >>> turtle.goto(-200,25)
2769   >>> turtle.pendown()
2770   >>> turtle.write("No one expects the Spanish Inquisition!",
2771   ...      font=("Arial", 20, "normal"))
2772   >>> turtle.penup()
2773   >>> turtle.goto(-100,-50)
2774   >>> turtle.pendown()
2775   >>> turtle.write("Our two chief Turtles are...",
2776   ...      font=("Arial", 16, "normal"))
2777   >>> turtle.penup()
2778   >>> turtle.goto(-450,-75)
2779   >>> turtle.write(str(turtles()))
2780