• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1========================================
2:mod:`turtle` --- Turtle graphics for Tk
3========================================
4
5.. module:: turtle
6   :synopsis: Turtle graphics for Tk
7.. sectionauthor:: Gregor Lingl <gregor.lingl@aon.at>
8
9.. testsetup:: default
10
11   from turtle import *
12   turtle = Turtle()
13
14Introduction
15============
16
17Turtle graphics is a popular way for introducing programming to kids.  It was
18part of the original Logo programming language developed by Wally Feurzig and
19Seymour Papert in 1966.
20
21Imagine a robotic turtle starting at (0, 0) in the x-y plane.  After an ``import turtle``, give it the
22command ``turtle.forward(15)``, and it moves (on-screen!) 15 pixels in the
23direction it is facing, drawing a line as it moves.  Give it the command
24``turtle.right(25)``, and it rotates in-place 25 degrees clockwise.
25
26By combining together these and similar commands, intricate shapes and pictures
27can easily be drawn.
28
29The :mod:`turtle` module is an extended reimplementation of the same-named
30module from the Python standard distribution up to version Python 2.5.
31
32It tries to keep the merits of the old turtle module and to be (nearly) 100%
33compatible with it.  This means in the first place to enable the learning
34programmer to use all the commands, classes and methods interactively when using
35the module from within IDLE run with the ``-n`` switch.
36
37The turtle module provides turtle graphics primitives, in both object-oriented
38and procedure-oriented ways.  Because it uses :mod:`Tkinter` for the underlying
39graphics, it needs a version of Python installed with Tk support.
40
41The object-oriented interface uses essentially two+two classes:
42
431. The :class:`TurtleScreen` class defines graphics windows as a playground for
44   the drawing turtles.  Its constructor needs a :class:`Tkinter.Canvas` or a
45   :class:`ScrolledCanvas` as argument.  It should be used when :mod:`turtle` is
46   used as part of some application.
47
48   The function :func:`Screen` returns a singleton object of a
49   :class:`TurtleScreen` subclass. This function should be used when
50   :mod:`turtle` is used as a standalone tool for doing graphics.
51   As a singleton object, inheriting from its class is not possible.
52
53   All methods of TurtleScreen/Screen also exist as functions, i.e. as part of
54   the procedure-oriented interface.
55
562. :class:`RawTurtle` (alias: :class:`RawPen`) defines Turtle objects which draw
57   on a :class:`TurtleScreen`.  Its constructor needs a Canvas, ScrolledCanvas
58   or TurtleScreen as argument, so the RawTurtle objects know where to draw.
59
60   Derived from RawTurtle is the subclass :class:`Turtle` (alias: :class:`Pen`),
61   which draws on "the" :class:`Screen` - instance which is automatically
62   created, if not already present.
63
64   All methods of RawTurtle/Turtle also exist as functions, i.e. part of the
65   procedure-oriented interface.
66
67The procedural interface provides functions which are derived from the methods
68of the classes :class:`Screen` and :class:`Turtle`.  They have the same names as
69the corresponding methods.  A screen object is automatically created whenever a
70function derived from a Screen method is called.  An (unnamed) turtle object is
71automatically created whenever any of the functions derived from a Turtle method
72is called.
73
74To use multiple turtles an a screen one has to use the object-oriented interface.
75
76.. note::
77   In the following documentation the argument list for functions is given.
78   Methods, of course, have the additional first argument *self* which is
79   omitted here.
80
81
82Overview over available Turtle and Screen methods
83=================================================
84
85Turtle methods
86--------------
87
88Turtle motion
89   Move and draw
90      | :func:`forward` | :func:`fd`
91      | :func:`backward` | :func:`bk` | :func:`back`
92      | :func:`right` | :func:`rt`
93      | :func:`left` | :func:`lt`
94      | :func:`goto` | :func:`setpos` | :func:`setposition`
95      | :func:`setx`
96      | :func:`sety`
97      | :func:`setheading` | :func:`seth`
98      | :func:`home`
99      | :func:`circle`
100      | :func:`dot`
101      | :func:`stamp`
102      | :func:`clearstamp`
103      | :func:`clearstamps`
104      | :func:`undo`
105      | :func:`speed`
106
107   Tell Turtle's state
108      | :func:`position` | :func:`pos`
109      | :func:`towards`
110      | :func:`xcor`
111      | :func:`ycor`
112      | :func:`heading`
113      | :func:`distance`
114
115   Setting and measurement
116      | :func:`degrees`
117      | :func:`radians`
118
119Pen control
120   Drawing state
121      | :func:`pendown` | :func:`pd` | :func:`down`
122      | :func:`penup` | :func:`pu` | :func:`up`
123      | :func:`pensize` | :func:`width`
124      | :func:`pen`
125      | :func:`isdown`
126
127   Color control
128      | :func:`color`
129      | :func:`pencolor`
130      | :func:`fillcolor`
131
132   Filling
133      | :func:`fill`
134      | :func:`begin_fill`
135      | :func:`end_fill`
136
137   More drawing control
138      | :func:`reset`
139      | :func:`clear`
140      | :func:`write`
141
142Turtle state
143   Visibility
144      | :func:`showturtle` | :func:`st`
145      | :func:`hideturtle` | :func:`ht`
146      | :func:`isvisible`
147
148   Appearance
149      | :func:`shape`
150      | :func:`resizemode`
151      | :func:`shapesize` | :func:`turtlesize`
152      | :func:`settiltangle`
153      | :func:`tiltangle`
154      | :func:`tilt`
155
156Using events
157   | :func:`onclick`
158   | :func:`onrelease`
159   | :func:`ondrag`
160   | :func:`mainloop` | :func:`done`
161
162Special Turtle methods
163   | :func:`begin_poly`
164   | :func:`end_poly`
165   | :func:`get_poly`
166   | :func:`clone`
167   | :func:`getturtle` | :func:`getpen`
168   | :func:`getscreen`
169   | :func:`setundobuffer`
170   | :func:`undobufferentries`
171   | :func:`tracer`
172   | :func:`window_width`
173   | :func:`window_height`
174
175
176Methods of TurtleScreen/Screen
177------------------------------
178
179Window control
180   | :func:`bgcolor`
181   | :func:`bgpic`
182   | :func:`clear` | :func:`clearscreen`
183   | :func:`reset` | :func:`resetscreen`
184   | :func:`screensize`
185   | :func:`setworldcoordinates`
186
187Animation control
188   | :func:`delay`
189   | :func:`tracer`
190   | :func:`update`
191
192Using screen events
193   | :func:`listen`
194   | :func:`onkey`
195   | :func:`onclick` | :func:`onscreenclick`
196   | :func:`ontimer`
197
198Settings and special methods
199   | :func:`mode`
200   | :func:`colormode`
201   | :func:`getcanvas`
202   | :func:`getshapes`
203   | :func:`register_shape` | :func:`addshape`
204   | :func:`turtles`
205   | :func:`window_height`
206   | :func:`window_width`
207
208Methods specific to Screen
209   | :func:`bye`
210   | :func:`exitonclick`
211   | :func:`setup`
212   | :func:`title`
213
214
215Methods of RawTurtle/Turtle and corresponding functions
216=======================================================
217
218Most of the examples in this section refer to a Turtle instance called
219``turtle``.
220
221Turtle motion
222-------------
223
224.. function:: forward(distance)
225              fd(distance)
226
227   :param distance: a number (integer or float)
228
229   Move the turtle forward by the specified *distance*, in the direction the
230   turtle is headed.
231
232   .. doctest::
233
234      >>> turtle.position()
235      (0.00,0.00)
236      >>> turtle.forward(25)
237      >>> turtle.position()
238      (25.00,0.00)
239      >>> turtle.forward(-75)
240      >>> turtle.position()
241      (-50.00,0.00)
242
243
244.. function:: back(distance)
245              bk(distance)
246              backward(distance)
247
248   :param distance: a number
249
250   Move the turtle backward by *distance*, opposite to the direction the
251   turtle is headed.  Do not change the turtle's heading.
252
253   .. doctest::
254      :hide:
255
256      >>> turtle.goto(0, 0)
257
258   .. doctest::
259
260      >>> turtle.position()
261      (0.00,0.00)
262      >>> turtle.backward(30)
263      >>> turtle.position()
264      (-30.00,0.00)
265
266
267.. function:: right(angle)
268              rt(angle)
269
270   :param angle: a number (integer or float)
271
272   Turn turtle right by *angle* units.  (Units are by default degrees, but
273   can be set via the :func:`degrees` and :func:`radians` functions.)  Angle
274   orientation depends on the turtle mode, see :func:`mode`.
275
276   .. doctest::
277      :hide:
278
279      >>> turtle.setheading(22)
280
281   .. doctest::
282
283      >>> turtle.heading()
284      22.0
285      >>> turtle.right(45)
286      >>> turtle.heading()
287      337.0
288
289
290.. function:: left(angle)
291              lt(angle)
292
293   :param angle: a number (integer or float)
294
295   Turn turtle left by *angle* units.  (Units are by default degrees, but
296   can be set via the :func:`degrees` and :func:`radians` functions.)  Angle
297   orientation depends on the turtle mode, see :func:`mode`.
298
299   .. doctest::
300      :hide:
301
302      >>> turtle.setheading(22)
303
304   .. doctest::
305
306      >>> turtle.heading()
307      22.0
308      >>> turtle.left(45)
309      >>> turtle.heading()
310      67.0
311
312
313.. function:: goto(x, y=None)
314              setpos(x, y=None)
315              setposition(x, y=None)
316
317   :param x: a number or a pair/vector of numbers
318   :param y: a number or ``None``
319
320   If *y* is ``None``, *x* must be a pair of coordinates or a :class:`Vec2D`
321   (e.g. as returned by :func:`pos`).
322
323   Move turtle to an absolute position.  If the pen is down, draw line.  Do
324   not change the turtle's orientation.
325
326   .. doctest::
327      :hide:
328
329      >>> turtle.goto(0, 0)
330
331   .. doctest::
332
333       >>> tp = turtle.pos()
334       >>> tp
335       (0.00,0.00)
336       >>> turtle.setpos(60,30)
337       >>> turtle.pos()
338       (60.00,30.00)
339       >>> turtle.setpos((20,80))
340       >>> turtle.pos()
341       (20.00,80.00)
342       >>> turtle.setpos(tp)
343       >>> turtle.pos()
344       (0.00,0.00)
345
346
347.. function:: setx(x)
348
349   :param x: a number (integer or float)
350
351   Set the turtle's first coordinate to *x*, leave second coordinate
352   unchanged.
353
354   .. doctest::
355      :hide:
356
357      >>> turtle.goto(0, 240)
358
359   .. doctest::
360
361      >>> turtle.position()
362      (0.00,240.00)
363      >>> turtle.setx(10)
364      >>> turtle.position()
365      (10.00,240.00)
366
367
368.. function:: sety(y)
369
370   :param y: a number (integer or float)
371
372   Set the turtle's second coordinate to *y*, leave first coordinate unchanged.
373
374   .. doctest::
375      :hide:
376
377      >>> turtle.goto(0, 40)
378
379   .. doctest::
380
381      >>> turtle.position()
382      (0.00,40.00)
383      >>> turtle.sety(-10)
384      >>> turtle.position()
385      (0.00,-10.00)
386
387
388.. function:: setheading(to_angle)
389              seth(to_angle)
390
391   :param to_angle: a number (integer or float)
392
393   Set the orientation of the turtle to *to_angle*.  Here are some common
394   directions in degrees:
395
396   =================== ====================
397    standard mode           logo mode
398   =================== ====================
399      0 - east                0 - north
400     90 - north              90 - east
401    180 - west              180 - south
402    270 - south             270 - west
403   =================== ====================
404
405   .. doctest::
406
407      >>> turtle.setheading(90)
408      >>> turtle.heading()
409      90.0
410
411
412.. function:: home()
413
414   Move turtle to the origin -- coordinates (0,0) -- and set its heading to
415   its start-orientation (which depends on the mode, see :func:`mode`).
416
417   .. doctest::
418      :hide:
419
420      >>> turtle.setheading(90)
421      >>> turtle.goto(0, -10)
422
423   .. doctest::
424
425      >>> turtle.heading()
426      90.0
427      >>> turtle.position()
428      (0.00,-10.00)
429      >>> turtle.home()
430      >>> turtle.position()
431      (0.00,0.00)
432      >>> turtle.heading()
433      0.0
434
435
436.. function:: circle(radius, extent=None, steps=None)
437
438   :param radius: a number
439   :param extent: a number (or ``None``)
440   :param steps: an integer (or ``None``)
441
442   Draw a circle with given *radius*.  The center is *radius* units left of
443   the turtle; *extent* -- an angle -- determines which part of the circle
444   is drawn.  If *extent* is not given, draw the entire circle.  If *extent*
445   is not a full circle, one endpoint of the arc is the current pen
446   position.  Draw the arc in counterclockwise direction if *radius* is
447   positive, otherwise in clockwise direction.  Finally the direction of the
448   turtle is changed by the amount of *extent*.
449
450   As the circle is approximated by an inscribed regular polygon, *steps*
451   determines the number of steps to use.  If not given, it will be
452   calculated automatically.  May be used to draw regular polygons.
453
454   .. doctest::
455
456      >>> turtle.home()
457      >>> turtle.position()
458      (0.00,0.00)
459      >>> turtle.heading()
460      0.0
461      >>> turtle.circle(50)
462      >>> turtle.position()
463      (-0.00,0.00)
464      >>> turtle.heading()
465      0.0
466      >>> turtle.circle(120, 180)  # draw a semicircle
467      >>> turtle.position()
468      (0.00,240.00)
469      >>> turtle.heading()
470      180.0
471
472
473.. function:: dot(size=None, *color)
474
475   :param size: an integer >= 1 (if given)
476   :param color: a colorstring or a numeric color tuple
477
478   Draw a circular dot with diameter *size*, using *color*.  If *size* is
479   not given, the maximum of pensize+4 and 2*pensize is used.
480
481
482   .. doctest::
483
484      >>> turtle.home()
485      >>> turtle.dot()
486      >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
487      >>> turtle.position()
488      (100.00,-0.00)
489      >>> turtle.heading()
490      0.0
491
492
493.. function:: stamp()
494
495   Stamp a copy of the turtle shape onto the canvas at the current turtle
496   position.  Return a stamp_id for that stamp, which can be used to delete
497   it by calling ``clearstamp(stamp_id)``.
498
499   .. doctest::
500
501      >>> turtle.color("blue")
502      >>> turtle.stamp()
503      11
504      >>> turtle.fd(50)
505
506
507.. function:: clearstamp(stampid)
508
509   :param stampid: an integer, must be return value of previous
510                   :func:`stamp` call
511
512   Delete stamp with given *stampid*.
513
514   .. doctest::
515
516      >>> turtle.position()
517      (150.00,-0.00)
518      >>> turtle.color("blue")
519      >>> astamp = turtle.stamp()
520      >>> turtle.fd(50)
521      >>> turtle.position()
522      (200.00,-0.00)
523      >>> turtle.clearstamp(astamp)
524      >>> turtle.position()
525      (200.00,-0.00)
526
527
528.. function:: clearstamps(n=None)
529
530   :param n: an integer (or ``None``)
531
532   Delete all or first/last *n* of turtle's stamps.  If *n* is ``None``, delete
533   all stamps, if *n* > 0 delete first *n* stamps, else if *n* < 0 delete
534   last *n* stamps.
535
536   .. doctest::
537
538      >>> for i in range(8):
539      ...     turtle.stamp(); turtle.fd(30)
540      13
541      14
542      15
543      16
544      17
545      18
546      19
547      20
548      >>> turtle.clearstamps(2)
549      >>> turtle.clearstamps(-2)
550      >>> turtle.clearstamps()
551
552
553.. function:: undo()
554
555   Undo (repeatedly) the last turtle action(s).  Number of available
556   undo actions is determined by the size of the undobuffer.
557
558   .. doctest::
559
560      >>> for i in range(4):
561      ...     turtle.fd(50); turtle.lt(80)
562      ...
563      >>> for i in range(8):
564      ...     turtle.undo()
565
566
567.. function:: speed(speed=None)
568
569   :param speed: an integer in the range 0..10 or a speedstring (see below)
570
571   Set the turtle's speed to an integer value in the range 0..10.  If no
572   argument is given, return current speed.
573
574   If input is a number greater than 10 or smaller than 0.5, speed is set
575   to 0.  Speedstrings are mapped to speedvalues as follows:
576
577   * "fastest":  0
578   * "fast":  10
579   * "normal":  6
580   * "slow":  3
581   * "slowest":  1
582
583   Speeds from 1 to 10 enforce increasingly faster animation of line drawing
584   and turtle turning.
585
586   Attention: *speed* = 0 means that *no* animation takes
587   place. forward/back makes turtle jump and likewise left/right make the
588   turtle turn instantly.
589
590   .. doctest::
591
592      >>> turtle.speed()
593      3
594      >>> turtle.speed('normal')
595      >>> turtle.speed()
596      6
597      >>> turtle.speed(9)
598      >>> turtle.speed()
599      9
600
601
602Tell Turtle's state
603-------------------
604
605.. function:: position()
606              pos()
607
608   Return the turtle's current location (x,y) (as a :class:`Vec2D` vector).
609
610   .. doctest::
611
612      >>> turtle.pos()
613      (440.00,-0.00)
614
615
616.. function:: towards(x, y=None)
617
618   :param x: a number or a pair/vector of numbers or a turtle instance
619   :param y: a number if *x* is a number, else ``None``
620
621   Return the angle between the line from turtle position to position specified
622   by (x,y), the vector or the other turtle.  This depends on the turtle's start
623   orientation which depends on the mode - "standard"/"world" or "logo").
624
625   .. doctest::
626
627      >>> turtle.goto(10, 10)
628      >>> turtle.towards(0,0)
629      225.0
630
631
632.. function:: xcor()
633
634   Return the turtle's x coordinate.
635
636   .. doctest::
637
638      >>> turtle.home()
639      >>> turtle.left(50)
640      >>> turtle.forward(100)
641      >>> turtle.pos()
642      (64.28,76.60)
643      >>> print turtle.xcor()
644      64.2787609687
645
646
647.. function:: ycor()
648
649   Return the turtle's y coordinate.
650
651   .. doctest::
652
653      >>> turtle.home()
654      >>> turtle.left(60)
655      >>> turtle.forward(100)
656      >>> print turtle.pos()
657      (50.00,86.60)
658      >>> print turtle.ycor()
659      86.6025403784
660
661
662.. function:: heading()
663
664   Return the turtle's current heading (value depends on the turtle mode, see
665   :func:`mode`).
666
667   .. doctest::
668
669      >>> turtle.home()
670      >>> turtle.left(67)
671      >>> turtle.heading()
672      67.0
673
674
675.. function:: distance(x, y=None)
676
677   :param x: a number or a pair/vector of numbers or a turtle instance
678   :param y: a number if *x* is a number, else ``None``
679
680   Return the distance from the turtle to (x,y), the given vector, or the given
681   other turtle, in turtle step units.
682
683   .. doctest::
684
685      >>> turtle.home()
686      >>> turtle.distance(30,40)
687      50.0
688      >>> turtle.distance((30,40))
689      50.0
690      >>> joe = Turtle()
691      >>> joe.forward(77)
692      >>> turtle.distance(joe)
693      77.0
694
695
696Settings for measurement
697------------------------
698
699.. function:: degrees(fullcircle=360.0)
700
701   :param fullcircle: a number
702
703   Set angle measurement units, i.e. set number of "degrees" for a full circle.
704   Default value is 360 degrees.
705
706   .. doctest::
707
708      >>> turtle.home()
709      >>> turtle.left(90)
710      >>> turtle.heading()
711      90.0
712
713      Change angle measurement unit to grad (also known as gon,
714      grade, or gradian and equals 1/100-th of the right angle.)
715      >>> turtle.degrees(400.0)
716      >>> turtle.heading()
717      100.0
718      >>> turtle.degrees(360)
719      >>> turtle.heading()
720      90.0
721
722
723.. function:: radians()
724
725   Set the angle measurement units to radians.  Equivalent to
726   ``degrees(2*math.pi)``.
727
728   .. doctest::
729
730      >>> turtle.home()
731      >>> turtle.left(90)
732      >>> turtle.heading()
733      90.0
734      >>> turtle.radians()
735      >>> turtle.heading()
736      1.5707963267948966
737
738   .. doctest::
739      :hide:
740
741      >>> turtle.degrees(360)
742
743
744Pen control
745-----------
746
747Drawing state
748~~~~~~~~~~~~~
749
750.. function:: pendown()
751              pd()
752              down()
753
754   Pull the pen down -- drawing when moving.
755
756
757.. function:: penup()
758              pu()
759              up()
760
761   Pull the pen up -- no drawing when moving.
762
763
764.. function:: pensize(width=None)
765              width(width=None)
766
767   :param width: a positive number
768
769   Set the line thickness to *width* or return it.  If resizemode is set to
770   "auto" and turtleshape is a polygon, that polygon is drawn with the same line
771   thickness.  If no argument is given, the current pensize is returned.
772
773   .. doctest::
774
775      >>> turtle.pensize()
776      1
777      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn
778
779
780.. function:: pen(pen=None, **pendict)
781
782   :param pen: a dictionary with some or all of the below listed keys
783   :param pendict: one or more keyword-arguments with the below listed keys as keywords
784
785   Return or set the pen's attributes in a "pen-dictionary" with the following
786   key/value pairs:
787
788   * "shown": True/False
789   * "pendown": True/False
790   * "pencolor": color-string or color-tuple
791   * "fillcolor": color-string or color-tuple
792   * "pensize": positive number
793   * "speed": number in range 0..10
794   * "resizemode": "auto" or "user" or "noresize"
795   * "stretchfactor": (positive number, positive number)
796   * "outline": positive number
797   * "tilt": number
798
799   This dictionary can be used as argument for a subsequent call to :func:`pen`
800   to restore the former pen-state.  Moreover one or more of these attributes
801   can be provided as keyword-arguments.  This can be used to set several pen
802   attributes in one statement.
803
804   .. doctest::
805      :options: +NORMALIZE_WHITESPACE
806
807      >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
808      >>> sorted(turtle.pen().items())
809      [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
810       ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
811       ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]
812      >>> penstate=turtle.pen()
813      >>> turtle.color("yellow", "")
814      >>> turtle.penup()
815      >>> sorted(turtle.pen().items())
816      [('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow'),
817       ('pendown', False), ('pensize', 10), ('resizemode', 'noresize'),
818       ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]
819      >>> turtle.pen(penstate, fillcolor="green")
820      >>> sorted(turtle.pen().items())
821      [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red'),
822       ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
823       ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]
824
825
826.. function:: isdown()
827
828   Return ``True`` if pen is down, ``False`` if it's up.
829
830   .. doctest::
831
832      >>> turtle.penup()
833      >>> turtle.isdown()
834      False
835      >>> turtle.pendown()
836      >>> turtle.isdown()
837      True
838
839
840Color control
841~~~~~~~~~~~~~
842
843.. function:: pencolor(*args)
844
845   Return or set the pencolor.
846
847   Four input formats are allowed:
848
849   ``pencolor()``
850      Return the current pencolor as color specification string or
851      as a tuple (see example).  May be used as input to another
852      color/pencolor/fillcolor call.
853
854   ``pencolor(colorstring)``
855      Set pencolor to *colorstring*, which is a Tk color specification string,
856      such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
857
858   ``pencolor((r, g, b))``
859      Set pencolor to the RGB color represented by the tuple of *r*, *g*, and
860      *b*.  Each of *r*, *g*, and *b* must be in the range 0..colormode, where
861      colormode is either 1.0 or 255 (see :func:`colormode`).
862
863   ``pencolor(r, g, b)``
864      Set pencolor to the RGB color represented by *r*, *g*, and *b*.  Each of
865      *r*, *g*, and *b* must be in the range 0..colormode.
866
867    If turtleshape is a polygon, the outline of that polygon is drawn with the
868    newly set pencolor.
869
870   .. doctest::
871
872       >>> colormode()
873       1.0
874       >>> turtle.pencolor()
875       'red'
876       >>> turtle.pencolor("brown")
877       >>> turtle.pencolor()
878       'brown'
879       >>> tup = (0.2, 0.8, 0.55)
880       >>> turtle.pencolor(tup)
881       >>> turtle.pencolor()
882       (0.2, 0.8, 0.5490196078431373)
883       >>> colormode(255)
884       >>> turtle.pencolor()
885       (51, 204, 140)
886       >>> turtle.pencolor('#32c18f')
887       >>> turtle.pencolor()
888       (50, 193, 143)
889
890
891.. function:: fillcolor(*args)
892
893   Return or set the fillcolor.
894
895   Four input formats are allowed:
896
897   ``fillcolor()``
898      Return the current fillcolor as color specification string, possibly
899      in tuple format (see example).  May be used as input to another
900      color/pencolor/fillcolor call.
901
902   ``fillcolor(colorstring)``
903      Set fillcolor to *colorstring*, which is a Tk color specification string,
904      such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
905
906   ``fillcolor((r, g, b))``
907      Set fillcolor to the RGB color represented by the tuple of *r*, *g*, and
908      *b*.  Each of *r*, *g*, and *b* must be in the range 0..colormode, where
909      colormode is either 1.0 or 255 (see :func:`colormode`).
910
911   ``fillcolor(r, g, b)``
912      Set fillcolor to the RGB color represented by *r*, *g*, and *b*.  Each of
913      *r*, *g*, and *b* must be in the range 0..colormode.
914
915    If turtleshape is a polygon, the interior of that polygon is drawn
916    with the newly set fillcolor.
917
918   .. doctest::
919
920       >>> turtle.fillcolor("violet")
921       >>> turtle.fillcolor()
922       'violet'
923       >>> col = turtle.pencolor()
924       >>> col
925       (50, 193, 143)
926       >>> turtle.fillcolor(col)
927       >>> turtle.fillcolor()
928       (50, 193, 143)
929       >>> turtle.fillcolor('#ffffff')
930       >>> turtle.fillcolor()
931       (255, 255, 255)
932
933
934.. function:: color(*args)
935
936   Return or set pencolor and fillcolor.
937
938   Several input formats are allowed.  They use 0 to 3 arguments as
939   follows:
940
941   ``color()``
942      Return the current pencolor and the current fillcolor as a pair of color
943      specification strings or tuples as returned by :func:`pencolor` and
944      :func:`fillcolor`.
945
946   ``color(colorstring)``, ``color((r,g,b))``, ``color(r,g,b)``
947      Inputs as in :func:`pencolor`, set both, fillcolor and pencolor, to the
948      given value.
949
950   ``color(colorstring1, colorstring2)``, ``color((r1,g1,b1), (r2,g2,b2))``
951      Equivalent to ``pencolor(colorstring1)`` and ``fillcolor(colorstring2)``
952      and analogously if the other input format is used.
953
954    If turtleshape is a polygon, outline and interior of that polygon is drawn
955    with the newly set colors.
956
957   .. doctest::
958
959       >>> turtle.color("red", "green")
960       >>> turtle.color()
961       ('red', 'green')
962       >>> color("#285078", "#a0c8f0")
963       >>> color()
964       ((40, 80, 120), (160, 200, 240))
965
966
967See also: Screen method :func:`colormode`.
968
969
970Filling
971~~~~~~~
972
973.. doctest::
974   :hide:
975
976   >>> turtle.home()
977
978.. function:: fill(flag)
979
980   :param flag: True/False (or 1/0 respectively)
981
982   Call ``fill(True)`` before drawing the shape you want to fill, and
983   ``fill(False)`` when done.  When used without argument: return fillstate
984   (``True`` if filling, ``False`` else).
985
986   .. doctest::
987
988      >>> turtle.fill(True)
989      >>> for _ in range(3):
990      ...    turtle.forward(100)
991      ...    turtle.left(120)
992      ...
993      >>> turtle.fill(False)
994
995
996.. function:: begin_fill()
997
998   Call just before drawing a shape to be filled.  Equivalent to ``fill(True)``.
999
1000
1001.. function:: end_fill()
1002
1003   Fill the shape drawn after the last call to :func:`begin_fill`.  Equivalent
1004   to ``fill(False)``.
1005
1006   .. doctest::
1007
1008      >>> turtle.color("black", "red")
1009      >>> turtle.begin_fill()
1010      >>> turtle.circle(80)
1011      >>> turtle.end_fill()
1012
1013
1014More drawing control
1015~~~~~~~~~~~~~~~~~~~~
1016
1017.. function:: reset()
1018
1019   Delete the turtle's drawings from the screen, re-center the turtle and set
1020   variables to the default values.
1021
1022   .. doctest::
1023
1024      >>> turtle.goto(0,-22)
1025      >>> turtle.left(100)
1026      >>> turtle.position()
1027      (0.00,-22.00)
1028      >>> turtle.heading()
1029      100.0
1030      >>> turtle.reset()
1031      >>> turtle.position()
1032      (0.00,0.00)
1033      >>> turtle.heading()
1034      0.0
1035
1036
1037.. function:: clear()
1038
1039   Delete the turtle's drawings from the screen.  Do not move turtle.  State and
1040   position of the turtle as well as drawings of other turtles are not affected.
1041
1042
1043.. function:: write(arg, move=False, align="left", font=("Arial", 8, "normal"))
1044
1045   :param arg: object to be written to the TurtleScreen
1046   :param move: True/False
1047   :param align: one of the strings "left", "center" or right"
1048   :param font: a triple (fontname, fontsize, fonttype)
1049
1050   Write text - the string representation of *arg* - at the current turtle
1051   position according to *align* ("left", "center" or right") and with the given
1052   font.  If *move* is true, the pen is moved to the bottom-right corner of the
1053   text.  By default, *move* is ``False``.
1054
1055   >>> turtle.write("Home = ", True, align="center")
1056   >>> turtle.write((0,0), True)
1057
1058
1059Turtle state
1060------------
1061
1062Visibility
1063~~~~~~~~~~
1064
1065.. function:: hideturtle()
1066              ht()
1067
1068   Make the turtle invisible.  It's a good idea to do this while you're in the
1069   middle of doing some complex drawing, because hiding the turtle speeds up the
1070   drawing observably.
1071
1072   .. doctest::
1073
1074      >>> turtle.hideturtle()
1075
1076
1077.. function:: showturtle()
1078              st()
1079
1080   Make the turtle visible.
1081
1082   .. doctest::
1083
1084      >>> turtle.showturtle()
1085
1086
1087.. function:: isvisible()
1088
1089   Return ``True`` if the Turtle is shown, ``False`` if it's hidden.
1090
1091   >>> turtle.hideturtle()
1092   >>> turtle.isvisible()
1093   False
1094   >>> turtle.showturtle()
1095   >>> turtle.isvisible()
1096   True
1097
1098
1099Appearance
1100~~~~~~~~~~
1101
1102.. function:: shape(name=None)
1103
1104   :param name: a string which is a valid shapename
1105
1106   Set turtle shape to shape with given *name* or, if name is not given, return
1107   name of current shape.  Shape with *name* must exist in the TurtleScreen's
1108   shape dictionary.  Initially there are the following polygon shapes: "arrow",
1109   "turtle", "circle", "square", "triangle", "classic".  To learn about how to
1110   deal with shapes see Screen method :func:`register_shape`.
1111
1112   .. doctest::
1113
1114      >>> turtle.shape()
1115      'classic'
1116      >>> turtle.shape("turtle")
1117      >>> turtle.shape()
1118      'turtle'
1119
1120
1121.. function:: resizemode(rmode=None)
1122
1123   :param rmode: one of the strings "auto", "user", "noresize"
1124
1125   Set resizemode to one of the values: "auto", "user", "noresize".  If *rmode*
1126   is not given, return current resizemode.  Different resizemodes have the
1127   following effects:
1128
1129   - "auto": adapts the appearance of the turtle corresponding to the value of pensize.
1130   - "user": adapts the appearance of the turtle according to the values of
1131     stretchfactor and outlinewidth (outline), which are set by
1132     :func:`shapesize`.
1133   - "noresize": no adaption of the turtle's appearance takes place.
1134
1135   resizemode("user") is called by :func:`shapesize` when used with arguments.
1136
1137   .. doctest::
1138
1139      >>> turtle.resizemode()
1140      'noresize'
1141      >>> turtle.resizemode("auto")
1142      >>> turtle.resizemode()
1143      'auto'
1144
1145
1146.. function:: shapesize(stretch_wid=None, stretch_len=None, outline=None)
1147              turtlesize(stretch_wid=None, stretch_len=None, outline=None)
1148
1149   :param stretch_wid: positive number
1150   :param stretch_len: positive number
1151   :param outline: positive number
1152
1153   Return or set the pen's attributes x/y-stretchfactors and/or outline.  Set
1154   resizemode to "user".  If and only if resizemode is set to "user", the turtle
1155   will be displayed stretched according to its stretchfactors: *stretch_wid* is
1156   stretchfactor perpendicular to its orientation, *stretch_len* is
1157   stretchfactor in direction of its orientation, *outline* determines the width
1158   of the shapes's outline.
1159
1160   .. doctest::
1161
1162      >>> turtle.shapesize()
1163      (1, 1, 1)
1164      >>> turtle.resizemode("user")
1165      >>> turtle.shapesize(5, 5, 12)
1166      >>> turtle.shapesize()
1167      (5, 5, 12)
1168      >>> turtle.shapesize(outline=8)
1169      >>> turtle.shapesize()
1170      (5, 5, 8)
1171
1172
1173.. function:: tilt(angle)
1174
1175   :param angle: a number
1176
1177   Rotate the turtleshape by *angle* from its current tilt-angle, but do *not*
1178   change the turtle's heading (direction of movement).
1179
1180   .. doctest::
1181
1182      >>> turtle.reset()
1183      >>> turtle.shape("circle")
1184      >>> turtle.shapesize(5,2)
1185      >>> turtle.tilt(30)
1186      >>> turtle.fd(50)
1187      >>> turtle.tilt(30)
1188      >>> turtle.fd(50)
1189
1190
1191.. function:: settiltangle(angle)
1192
1193   :param angle: a number
1194
1195   Rotate the turtleshape to point in the direction specified by *angle*,
1196   regardless of its current tilt-angle.  *Do not* change the turtle's heading
1197   (direction of movement).
1198
1199   .. doctest::
1200
1201      >>> turtle.reset()
1202      >>> turtle.shape("circle")
1203      >>> turtle.shapesize(5,2)
1204      >>> turtle.settiltangle(45)
1205      >>> turtle.fd(50)
1206      >>> turtle.settiltangle(-45)
1207      >>> turtle.fd(50)
1208
1209
1210.. function:: tiltangle()
1211
1212   Return the current tilt-angle, i.e. the angle between the orientation of the
1213   turtleshape and the heading of the turtle (its direction of movement).
1214
1215   .. doctest::
1216
1217      >>> turtle.reset()
1218      >>> turtle.shape("circle")
1219      >>> turtle.shapesize(5,2)
1220      >>> turtle.tilt(45)
1221      >>> turtle.tiltangle()
1222      45.0
1223
1224
1225Using events
1226------------
1227
1228.. function:: onclick(fun, btn=1, add=None)
1229
1230   :param fun: a function with two arguments which will be called with the
1231               coordinates of the clicked point on the canvas
1232   :param num: number of the mouse-button, defaults to 1 (left mouse button)
1233   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1234               added, otherwise it will replace a former binding
1235
1236   Bind *fun* to mouse-click events on this turtle.  If *fun* is ``None``,
1237   existing bindings are removed.  Example for the anonymous turtle, i.e. the
1238   procedural way:
1239
1240   .. doctest::
1241
1242      >>> def turn(x, y):
1243      ...     left(180)
1244      ...
1245      >>> onclick(turn)  # Now clicking into the turtle will turn it.
1246      >>> onclick(None)  # event-binding will be removed
1247
1248
1249.. function:: onrelease(fun, btn=1, add=None)
1250
1251   :param fun: a function with two arguments which will be called with the
1252               coordinates of the clicked point on the canvas
1253   :param num: number of the mouse-button, defaults to 1 (left mouse button)
1254   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1255               added, otherwise it will replace a former binding
1256
1257   Bind *fun* to mouse-button-release events on this turtle.  If *fun* is
1258   ``None``, existing bindings are removed.
1259
1260   .. doctest::
1261
1262      >>> class MyTurtle(Turtle):
1263      ...     def glow(self,x,y):
1264      ...         self.fillcolor("red")
1265      ...     def unglow(self,x,y):
1266      ...         self.fillcolor("")
1267      ...
1268      >>> turtle = MyTurtle()
1269      >>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
1270      >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
1271
1272
1273.. function:: ondrag(fun, btn=1, add=None)
1274
1275   :param fun: a function with two arguments which will be called with the
1276               coordinates of the clicked point on the canvas
1277   :param num: number of the mouse-button, defaults to 1 (left mouse button)
1278   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1279               added, otherwise it will replace a former binding
1280
1281   Bind *fun* to mouse-move events on this turtle.  If *fun* is ``None``,
1282   existing bindings are removed.
1283
1284   Remark: Every sequence of mouse-move-events on a turtle is preceded by a
1285   mouse-click event on that turtle.
1286
1287   .. doctest::
1288
1289      >>> turtle.ondrag(turtle.goto)
1290
1291   Subsequently, clicking and dragging the Turtle will move it across
1292   the screen thereby producing handdrawings (if pen is down).
1293
1294
1295.. function:: mainloop()
1296              done()
1297
1298   Starts event loop - calling Tkinter's mainloop function. Must be the last
1299   statement in a turtle graphics program.
1300
1301      >>> turtle.mainloop()
1302
1303
1304Special Turtle methods
1305----------------------
1306
1307.. function:: begin_poly()
1308
1309   Start recording the vertices of a polygon.  Current turtle position is first
1310   vertex of polygon.
1311
1312
1313.. function:: end_poly()
1314
1315   Stop recording the vertices of a polygon.  Current turtle position is last
1316   vertex of polygon.  This will be connected with the first vertex.
1317
1318
1319.. function:: get_poly()
1320
1321   Return the last recorded polygon.
1322
1323   .. doctest::
1324
1325      >>> turtle.home()
1326      >>> turtle.begin_poly()
1327      >>> turtle.fd(100)
1328      >>> turtle.left(20)
1329      >>> turtle.fd(30)
1330      >>> turtle.left(60)
1331      >>> turtle.fd(50)
1332      >>> turtle.end_poly()
1333      >>> p = turtle.get_poly()
1334      >>> register_shape("myFavouriteShape", p)
1335
1336
1337.. function:: clone()
1338
1339   Create and return a clone of the turtle with same position, heading and
1340   turtle properties.
1341
1342   .. doctest::
1343
1344      >>> mick = Turtle()
1345      >>> joe = mick.clone()
1346
1347
1348.. function:: getturtle()
1349              getpen()
1350
1351   Return the Turtle object itself.  Only reasonable use: as a function to
1352   return the "anonymous turtle":
1353
1354   .. doctest::
1355
1356      >>> pet = getturtle()
1357      >>> pet.fd(50)
1358      >>> pet
1359      <turtle.Turtle object at 0x...>
1360
1361
1362.. function:: getscreen()
1363
1364   Return the :class:`TurtleScreen` object the turtle is drawing on.
1365   TurtleScreen methods can then be called for that object.
1366
1367   .. doctest::
1368
1369      >>> ts = turtle.getscreen()
1370      >>> ts
1371      <turtle._Screen object at 0x...>
1372      >>> ts.bgcolor("pink")
1373
1374
1375.. function:: setundobuffer(size)
1376
1377   :param size: an integer or ``None``
1378
1379   Set or disable undobuffer.  If *size* is an integer an empty undobuffer of
1380   given size is installed.  *size* gives the maximum number of turtle actions
1381   that can be undone by the :func:`undo` method/function.  If *size* is
1382   ``None``, the undobuffer is disabled.
1383
1384   .. doctest::
1385
1386      >>> turtle.setundobuffer(42)
1387
1388
1389.. function:: undobufferentries()
1390
1391   Return number of entries in the undobuffer.
1392
1393   .. doctest::
1394
1395      >>> while undobufferentries():
1396      ...     undo()
1397
1398
1399.. function:: tracer(flag=None, delay=None)
1400
1401   A replica of the corresponding TurtleScreen method.
1402
1403   .. deprecated:: 2.6
1404
1405
1406.. function:: window_width()
1407              window_height()
1408
1409   Both are replicas of the corresponding TurtleScreen methods.
1410
1411   .. deprecated:: 2.6
1412
1413
1414.. _compoundshapes:
1415
1416Excursus about the use of compound shapes
1417-----------------------------------------
1418
1419To use compound turtle shapes, which consist of several polygons of different
1420color, you must use the helper class :class:`Shape` explicitly as described
1421below:
1422
14231. Create an empty Shape object of type "compound".
14242. Add as many components to this object as desired, using the
1425   :meth:`addcomponent` method.
1426
1427   For example:
1428
1429   .. doctest::
1430
1431      >>> s = Shape("compound")
1432      >>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
1433      >>> s.addcomponent(poly1, "red", "blue")
1434      >>> poly2 = ((0,0),(10,-5),(-10,-5))
1435      >>> s.addcomponent(poly2, "blue", "red")
1436
14373. Now add the Shape to the Screen's shapelist and use it:
1438
1439   .. doctest::
1440
1441      >>> register_shape("myshape", s)
1442      >>> shape("myshape")
1443
1444
1445.. note::
1446
1447   The :class:`Shape` class is used internally by the :func:`register_shape`
1448   method in different ways.  The application programmer has to deal with the
1449   Shape class *only* when using compound shapes like shown above!
1450
1451
1452Methods of TurtleScreen/Screen and corresponding functions
1453==========================================================
1454
1455Most of the examples in this section refer to a TurtleScreen instance called
1456``screen``.
1457
1458.. doctest::
1459   :hide:
1460
1461   >>> screen = Screen()
1462
1463Window control
1464--------------
1465
1466.. function:: bgcolor(*args)
1467
1468   :param args: a color string or three numbers in the range 0..colormode or a
1469                3-tuple of such numbers
1470
1471
1472   Set or return background color of the TurtleScreen.
1473
1474   .. doctest::
1475
1476      >>> screen.bgcolor("orange")
1477      >>> screen.bgcolor()
1478      'orange'
1479      >>> screen.bgcolor("#800080")
1480      >>> screen.bgcolor()
1481      (128, 0, 128)
1482
1483
1484.. function:: bgpic(picname=None)
1485
1486   :param picname: a string, name of a gif-file or ``"nopic"``, or ``None``
1487
1488   Set background image or return name of current backgroundimage.  If *picname*
1489   is a filename, set the corresponding image as background.  If *picname* is
1490   ``"nopic"``, delete background image, if present.  If *picname* is ``None``,
1491   return the filename of the current backgroundimage. ::
1492
1493       >>> screen.bgpic()
1494       'nopic'
1495       >>> screen.bgpic("landscape.gif")
1496       >>> screen.bgpic()
1497       "landscape.gif"
1498
1499
1500.. function:: clear()
1501              clearscreen()
1502
1503   Delete all drawings and all turtles from the TurtleScreen.  Reset the now
1504   empty TurtleScreen to its initial state: white background, no background
1505   image, no event bindings and tracing on.
1506
1507   .. note::
1508      This TurtleScreen method is available as a global function only under the
1509      name ``clearscreen``.  The global function ``clear`` is another one
1510      derived from the Turtle method ``clear``.
1511
1512
1513.. function:: reset()
1514              resetscreen()
1515
1516   Reset all Turtles on the Screen to their initial state.
1517
1518   .. note::
1519      This TurtleScreen method is available as a global function only under the
1520      name ``resetscreen``.  The global function ``reset`` is another one
1521      derived from the Turtle method ``reset``.
1522
1523
1524.. function:: screensize(canvwidth=None, canvheight=None, bg=None)
1525
1526   :param canvwidth: positive integer, new width of canvas in pixels
1527   :param canvheight: positive integer, new height of canvas in pixels
1528   :param bg: colorstring or color-tuple, new background color
1529
1530   If no arguments are given, return current (canvaswidth, canvasheight).  Else
1531   resize the canvas the turtles are drawing on.  Do not alter the drawing
1532   window.  To observe hidden parts of the canvas, use the scrollbars. With this
1533   method, one can make visible those parts of a drawing which were outside the
1534   canvas before.
1535
1536      >>> screen.screensize()
1537      (400, 300)
1538      >>> screen.screensize(2000,1500)
1539      >>> screen.screensize()
1540      (2000, 1500)
1541
1542   e.g. to search for an erroneously escaped turtle ;-)
1543
1544
1545.. function:: setworldcoordinates(llx, lly, urx, ury)
1546
1547   :param llx: a number, x-coordinate of lower left corner of canvas
1548   :param lly: a number, y-coordinate of lower left corner of canvas
1549   :param urx: a number, x-coordinate of upper right corner of canvas
1550   :param ury: a number, y-coordinate of upper right corner of canvas
1551
1552   Set up user-defined coordinate system and switch to mode "world" if
1553   necessary.  This performs a ``screen.reset()``.  If mode "world" is already
1554   active, all drawings are redrawn according to the new coordinates.
1555
1556   **ATTENTION**: in user-defined coordinate systems angles may appear
1557   distorted.
1558
1559   .. doctest::
1560
1561      >>> screen.reset()
1562      >>> screen.setworldcoordinates(-50,-7.5,50,7.5)
1563      >>> for _ in range(72):
1564      ...     left(10)
1565      ...
1566      >>> for _ in range(8):
1567      ...     left(45); fd(2)   # a regular octagon
1568
1569   .. doctest::
1570      :hide:
1571
1572      >>> screen.reset()
1573      >>> for t in turtles():
1574      ...      t.reset()
1575
1576
1577Animation control
1578-----------------
1579
1580.. function:: delay(delay=None)
1581
1582   :param delay: positive integer
1583
1584   Set or return the drawing *delay* in milliseconds.  (This is approximately
1585   the time interval between two consecutive canvas updates.)  The longer the
1586   drawing delay, the slower the animation.
1587
1588   Optional argument:
1589
1590   .. doctest::
1591
1592      >>> screen.delay()
1593      10
1594      >>> screen.delay(5)
1595      >>> screen.delay()
1596      5
1597
1598
1599.. function:: tracer(n=None, delay=None)
1600
1601   :param n: nonnegative integer
1602   :param delay: nonnegative integer
1603
1604   Turn turtle animation on/off and set delay for update drawings.  If *n* is
1605   given, only each n-th regular screen update is really performed.  (Can be
1606   used to accelerate the drawing of complex graphics.)  Second argument sets
1607   delay value (see :func:`delay`).
1608
1609   .. doctest::
1610
1611      >>> screen.tracer(8, 25)
1612      >>> dist = 2
1613      >>> for i in range(200):
1614      ...     fd(dist)
1615      ...     rt(90)
1616      ...     dist += 2
1617
1618
1619.. function:: update()
1620
1621   Perform a TurtleScreen update. To be used when tracer is turned off.
1622
1623See also the RawTurtle/Turtle method :func:`speed`.
1624
1625
1626Using screen events
1627-------------------
1628
1629.. function:: listen(xdummy=None, ydummy=None)
1630
1631   Set focus on TurtleScreen (in order to collect key-events).  Dummy arguments
1632   are provided in order to be able to pass :func:`listen` to the onclick method.
1633
1634
1635.. function:: onkey(fun, key)
1636
1637   :param fun: a function with no arguments or ``None``
1638   :param key: a string: key (e.g. "a") or key-symbol (e.g. "space")
1639
1640   Bind *fun* to key-release event of key.  If *fun* is ``None``, event bindings
1641   are removed. Remark: in order to be able to register key-events, TurtleScreen
1642   must have the focus. (See method :func:`listen`.)
1643
1644   .. doctest::
1645
1646      >>> def f():
1647      ...     fd(50)
1648      ...     lt(60)
1649      ...
1650      >>> screen.onkey(f, "Up")
1651      >>> screen.listen()
1652
1653
1654.. function:: onclick(fun, btn=1, add=None)
1655              onscreenclick(fun, btn=1, add=None)
1656
1657   :param fun: a function with two arguments which will be called with the
1658               coordinates of the clicked point on the canvas
1659   :param num: number of the mouse-button, defaults to 1 (left mouse button)
1660   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
1661               added, otherwise it will replace a former binding
1662
1663   Bind *fun* to mouse-click events on this screen.  If *fun* is ``None``,
1664   existing bindings are removed.
1665
1666   Example for a TurtleScreen instance named ``screen`` and a Turtle instance
1667   named turtle:
1668
1669   .. doctest::
1670
1671      >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
1672      >>>                             # make the turtle move to the clicked point.
1673      >>> screen.onclick(None)        # remove event binding again
1674
1675   .. note::
1676      This TurtleScreen method is available as a global function only under the
1677      name ``onscreenclick``.  The global function ``onclick`` is another one
1678      derived from the Turtle method ``onclick``.
1679
1680
1681.. function:: ontimer(fun, t=0)
1682
1683   :param fun: a function with no arguments
1684   :param t: a number >= 0
1685
1686   Install a timer that calls *fun* after *t* milliseconds.
1687
1688   .. doctest::
1689
1690      >>> running = True
1691      >>> def f():
1692      ...     if running:
1693      ...         fd(50)
1694      ...         lt(60)
1695      ...         screen.ontimer(f, 250)
1696      >>> f()   ### makes the turtle march around
1697      >>> running = False
1698
1699
1700Settings and special methods
1701----------------------------
1702
1703.. function:: mode(mode=None)
1704
1705   :param mode: one of the strings "standard", "logo" or "world"
1706
1707   Set turtle mode ("standard", "logo" or "world") and perform reset.  If mode
1708   is not given, current mode is returned.
1709
1710   Mode "standard" is compatible with old :mod:`turtle`.  Mode "logo" is
1711   compatible with most Logo turtle graphics.  Mode "world" uses user-defined
1712   "world coordinates". **Attention**: in this mode angles appear distorted if
1713   ``x/y`` unit-ratio doesn't equal 1.
1714
1715   ============ ========================= ===================
1716       Mode      Initial turtle heading     positive angles
1717   ============ ========================= ===================
1718    "standard"    to the right (east)       counterclockwise
1719      "logo"        upward    (north)         clockwise
1720   ============ ========================= ===================
1721
1722   .. doctest::
1723
1724      >>> mode("logo")   # resets turtle heading to north
1725      >>> mode()
1726      'logo'
1727
1728
1729.. function:: colormode(cmode=None)
1730
1731   :param cmode: one of the values 1.0 or 255
1732
1733   Return the colormode or set it to 1.0 or 255.  Subsequently *r*, *g*, *b*
1734   values of color triples have to be in the range 0..\ *cmode*.
1735
1736   .. doctest::
1737
1738      >>> screen.colormode(1)
1739      >>> turtle.pencolor(240, 160, 80)
1740      Traceback (most recent call last):
1741           ...
1742      TurtleGraphicsError: bad color sequence: (240, 160, 80)
1743      >>> screen.colormode()
1744      1.0
1745      >>> screen.colormode(255)
1746      >>> screen.colormode()
1747      255
1748      >>> turtle.pencolor(240,160,80)
1749
1750
1751.. function:: getcanvas()
1752
1753   Return the Canvas of this TurtleScreen.  Useful for insiders who know what to
1754   do with a Tkinter Canvas.
1755
1756   .. doctest::
1757
1758      >>> cv = screen.getcanvas()
1759      >>> cv
1760      <turtle.ScrolledCanvas instance at 0x...>
1761
1762
1763.. function:: getshapes()
1764
1765   Return a list of names of all currently available turtle shapes.
1766
1767   .. doctest::
1768
1769      >>> screen.getshapes()
1770      ['arrow', 'blank', 'circle', ..., 'turtle']
1771
1772
1773.. function:: register_shape(name, shape=None)
1774              addshape(name, shape=None)
1775
1776   There are three different ways to call this function:
1777
1778   (1) *name* is the name of a gif-file and *shape* is ``None``: Install the
1779       corresponding image shape. ::
1780
1781       >>> screen.register_shape("turtle.gif")
1782
1783       .. note::
1784          Image shapes *do not* rotate when turning the turtle, so they do not
1785          display the heading of the turtle!
1786
1787   (2) *name* is an arbitrary string and *shape* is a tuple of pairs of
1788       coordinates: Install the corresponding polygon shape.
1789
1790       .. doctest::
1791
1792          >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
1793
1794   (3) *name* is an arbitrary string and shape is a (compound) :class:`Shape`
1795       object: Install the corresponding compound shape.
1796
1797   Add a turtle shape to TurtleScreen's shapelist.  Only thusly registered
1798   shapes can be used by issuing the command ``shape(shapename)``.
1799
1800
1801.. function:: turtles()
1802
1803   Return the list of turtles on the screen.
1804
1805   .. doctest::
1806
1807      >>> for turtle in screen.turtles():
1808      ...     turtle.color("red")
1809
1810
1811.. function:: window_height()
1812
1813   Return the height of the turtle window. ::
1814
1815       >>> screen.window_height()
1816       480
1817
1818
1819.. function:: window_width()
1820
1821   Return the width of the turtle window. ::
1822
1823       >>> screen.window_width()
1824       640
1825
1826
1827.. _screenspecific:
1828
1829Methods specific to Screen, not inherited from TurtleScreen
1830-----------------------------------------------------------
1831
1832.. function:: bye()
1833
1834   Shut the turtlegraphics window.
1835
1836
1837.. function:: exitonclick()
1838
1839   Bind bye() method to mouse clicks on the Screen.
1840
1841
1842   If the value "using_IDLE" in the configuration dictionary is ``False``
1843   (default value), also enter mainloop.  Remark: If IDLE with the ``-n`` switch
1844   (no subprocess) is used, this value should be set to ``True`` in
1845   :file:`turtle.cfg`.  In this case IDLE's own mainloop is active also for the
1846   client script.
1847
1848
1849.. function:: setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])
1850
1851   Set the size and position of the main window.  Default values of arguments
1852   are stored in the configuration dictionary and can be changed via a
1853   :file:`turtle.cfg` file.
1854
1855   :param width: if an integer, a size in pixels, if a float, a fraction of the
1856                 screen; default is 50% of screen
1857   :param height: if an integer, the height in pixels, if a float, a fraction of
1858                  the screen; default is 75% of screen
1859   :param startx: if positive, starting position in pixels from the left
1860                  edge of the screen, if negative from the right edge, if ``None``,
1861                  center window horizontally
1862   :param starty: if positive, starting position in pixels from the top
1863                  edge of the screen, if negative from the bottom edge, if ``None``,
1864                  center window vertically
1865
1866   .. doctest::
1867
1868      >>> screen.setup (width=200, height=200, startx=0, starty=0)
1869      >>>              # sets window to 200x200 pixels, in upper left of screen
1870      >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
1871      >>>              # sets window to 75% of screen by 50% of screen and centers
1872
1873
1874.. function:: title(titlestring)
1875
1876   :param titlestring: a string that is shown in the titlebar of the turtle
1877                       graphics window
1878
1879   Set title of turtle window to *titlestring*.
1880
1881   .. doctest::
1882
1883      >>> screen.title("Welcome to the turtle zoo!")
1884
1885
1886The public classes of the module :mod:`turtle`
1887==============================================
1888
1889
1890.. class:: RawTurtle(canvas)
1891           RawPen(canvas)
1892
1893   :param canvas: a :class:`Tkinter.Canvas`, a :class:`ScrolledCanvas` or a
1894                  :class:`TurtleScreen`
1895
1896   Create a turtle.  The turtle has all methods described above as "methods of
1897   Turtle/RawTurtle".
1898
1899
1900.. class:: Turtle()
1901
1902   Subclass of RawTurtle, has the same interface but draws on a default
1903   :class:`Screen` object created automatically when needed for the first time.
1904
1905
1906.. class:: TurtleScreen(cv)
1907
1908   :param cv: a :class:`Tkinter.Canvas`
1909
1910   Provides screen oriented methods like :func:`setbg` etc. that are described
1911   above.
1912
1913.. class:: Screen()
1914
1915   Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`.
1916
1917
1918.. class:: ScrolledCanvas(master)
1919
1920   :param master: some Tkinter widget to contain the ScrolledCanvas, i.e.
1921      a Tkinter-canvas with scrollbars added
1922
1923   Used by class Screen, which thus automatically provides a ScrolledCanvas as
1924   playground for the turtles.
1925
1926.. class:: Shape(type_, data)
1927
1928   :param type\_: one of the strings "polygon", "image", "compound"
1929
1930   Data structure modeling shapes.  The pair ``(type_, data)`` must follow this
1931   specification:
1932
1933
1934   =========== ===========
1935   *type_*     *data*
1936   =========== ===========
1937   "polygon"   a polygon-tuple, i.e. a tuple of pairs of coordinates
1938   "image"     an image  (in this form only used internally!)
1939   "compound"  ``None`` (a compound shape has to be constructed using the
1940               :meth:`addcomponent` method)
1941   =========== ===========
1942
1943   .. method:: addcomponent(poly, fill, outline=None)
1944
1945      :param poly: a polygon, i.e. a tuple of pairs of numbers
1946      :param fill: a color the *poly* will be filled with
1947      :param outline: a color for the poly's outline (if given)
1948
1949      Example:
1950
1951      .. doctest::
1952
1953         >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
1954         >>> s = Shape("compound")
1955         >>> s.addcomponent(poly, "red", "blue")
1956         >>> # ... add more components and then use register_shape()
1957
1958      See :ref:`compoundshapes`.
1959
1960
1961.. class:: Vec2D(x, y)
1962
1963   A two-dimensional vector class, used as a helper class for implementing
1964   turtle graphics.  May be useful for turtle graphics programs too.  Derived
1965   from tuple, so a vector is a tuple!
1966
1967   Provides (for *a*, *b* vectors, *k* number):
1968
1969   * ``a + b`` vector addition
1970   * ``a - b`` vector subtraction
1971   * ``a * b`` inner product
1972   * ``k * a`` and ``a * k`` multiplication with scalar
1973   * ``abs(a)`` absolute value of a
1974   * ``a.rotate(angle)`` rotation
1975
1976
1977Help and configuration
1978======================
1979
1980How to use help
1981---------------
1982
1983The public methods of the Screen and Turtle classes are documented extensively
1984via docstrings.  So these can be used as online-help via the Python help
1985facilities:
1986
1987- When using IDLE, tooltips show the signatures and first lines of the
1988  docstrings of typed in function-/method calls.
1989
1990- Calling :func:`help` on methods or functions displays the docstrings::
1991
1992     >>> help(Screen.bgcolor)
1993     Help on method bgcolor in module turtle:
1994
1995     bgcolor(self, *args) unbound turtle.Screen method
1996         Set or return backgroundcolor of the TurtleScreen.
1997
1998         Arguments (if given): a color string or three numbers
1999         in the range 0..colormode or a 3-tuple of such numbers.
2000
2001
2002           >>> screen.bgcolor("orange")
2003           >>> screen.bgcolor()
2004           "orange"
2005           >>> screen.bgcolor(0.5,0,0.5)
2006           >>> screen.bgcolor()
2007           "#800080"
2008
2009     >>> help(Turtle.penup)
2010     Help on method penup in module turtle:
2011
2012     penup(self) unbound turtle.Turtle method
2013         Pull the pen up -- no drawing when moving.
2014
2015         Aliases: penup | pu | up
2016
2017         No argument
2018
2019         >>> turtle.penup()
2020
2021- The docstrings of the functions which are derived from methods have a modified
2022  form::
2023
2024     >>> help(bgcolor)
2025     Help on function bgcolor in module turtle:
2026
2027     bgcolor(*args)
2028         Set or return backgroundcolor of the TurtleScreen.
2029
2030         Arguments (if given): a color string or three numbers
2031         in the range 0..colormode or a 3-tuple of such numbers.
2032
2033         Example::
2034
2035           >>> bgcolor("orange")
2036           >>> bgcolor()
2037           "orange"
2038           >>> bgcolor(0.5,0,0.5)
2039           >>> bgcolor()
2040           "#800080"
2041
2042     >>> help(penup)
2043     Help on function penup in module turtle:
2044
2045     penup()
2046         Pull the pen up -- no drawing when moving.
2047
2048         Aliases: penup | pu | up
2049
2050         No argument
2051
2052         Example:
2053         >>> penup()
2054
2055These modified docstrings are created automatically together with the function
2056definitions that are derived from the methods at import time.
2057
2058
2059Translation of docstrings into different languages
2060--------------------------------------------------
2061
2062There is a utility to create a dictionary the keys of which are the method names
2063and the values of which are the docstrings of the public methods of the classes
2064Screen and Turtle.
2065
2066.. function:: write_docstringdict(filename="turtle_docstringdict")
2067
2068   :param filename: a string, used as filename
2069
2070   Create and write docstring-dictionary to a Python script with the given
2071   filename.  This function has to be called explicitly (it is not used by the
2072   turtle graphics classes).  The docstring dictionary will be written to the
2073   Python script :file:`{filename}.py`.  It is intended to serve as a template
2074   for translation of the docstrings into different languages.
2075
2076If you (or your students) want to use :mod:`turtle` with online help in your
2077native language, you have to translate the docstrings and save the resulting
2078file as e.g. :file:`turtle_docstringdict_german.py`.
2079
2080If you have an appropriate entry in your :file:`turtle.cfg` file this dictionary
2081will be read in at import time and will replace the original English docstrings.
2082
2083At the time of this writing there are docstring dictionaries in German and in
2084Italian.  (Requests please to glingl@aon.at.)
2085
2086
2087
2088How to configure Screen and Turtles
2089-----------------------------------
2090
2091The built-in default configuration mimics the appearance and behaviour of the
2092old turtle module in order to retain best possible compatibility with it.
2093
2094If you want to use a different configuration which better reflects the features
2095of this module or which better fits to your needs, e.g. for use in a classroom,
2096you can prepare a configuration file ``turtle.cfg`` which will be read at import
2097time and modify the configuration according to its settings.
2098
2099The built in configuration would correspond to the following turtle.cfg::
2100
2101   width = 0.5
2102   height = 0.75
2103   leftright = None
2104   topbottom = None
2105   canvwidth = 400
2106   canvheight = 300
2107   mode = standard
2108   colormode = 1.0
2109   delay = 10
2110   undobuffersize = 1000
2111   shape = classic
2112   pencolor = black
2113   fillcolor = black
2114   resizemode = noresize
2115   visible = True
2116   language = english
2117   exampleturtle = turtle
2118   examplescreen = screen
2119   title = Python Turtle Graphics
2120   using_IDLE = False
2121
2122Short explanation of selected entries:
2123
2124- The first four lines correspond to the arguments of the :meth:`Screen.setup`
2125  method.
2126- Line 5 and 6 correspond to the arguments of the method
2127  :meth:`Screen.screensize`.
2128- *shape* can be any of the built-in shapes, e.g: arrow, turtle, etc.  For more
2129  info try ``help(shape)``.
2130- If you want to use no fillcolor (i.e. make the turtle transparent), you have
2131  to write ``fillcolor = ""`` (but all nonempty strings must not have quotes in
2132  the cfg-file).
2133- If you want to reflect the turtle its state, you have to use ``resizemode =
2134  auto``.
2135- If you set e.g. ``language = italian`` the docstringdict
2136  :file:`turtle_docstringdict_italian.py` will be loaded at import time (if
2137  present on the import path, e.g. in the same directory as :mod:`turtle`.
2138- The entries *exampleturtle* and *examplescreen* define the names of these
2139  objects as they occur in the docstrings.  The transformation of
2140  method-docstrings to function-docstrings will delete these names from the
2141  docstrings.
2142- *using_IDLE*: Set this to ``True`` if you regularly work with IDLE and its -n
2143  switch ("no subprocess").  This will prevent :func:`exitonclick` to enter the
2144  mainloop.
2145
2146There can be a :file:`turtle.cfg` file in the directory where :mod:`turtle` is
2147stored and an additional one in the current working directory.  The latter will
2148override the settings of the first one.
2149
2150The :file:`Demo/turtle` directory contains a :file:`turtle.cfg` file.  You can
2151study it as an example and see its effects when running the demos (preferably
2152not from within the demo-viewer).
2153
2154
2155Demo scripts
2156============
2157
2158There is a set of demo scripts in the turtledemo directory located in the
2159:file:`Demo/turtle` directory in the source distribution.
2160
2161It contains:
2162
2163- a set of 15 demo scripts demonstrating different features of the new module
2164  :mod:`turtle`
2165- a demo viewer :file:`turtleDemo.py` which can be used to view the sourcecode
2166  of the scripts and run them at the same time. 14 of the examples can be
2167  accessed via the Examples menu; all of them can also be run standalone.
2168- The example :file:`turtledemo_two_canvases.py` demonstrates the simultaneous
2169  use of two canvases with the turtle module.  Therefore it only can be run
2170  standalone.
2171- There is a :file:`turtle.cfg` file in this directory, which also serves as an
2172  example for how to write and use such files.
2173
2174The demoscripts are:
2175
2176.. tabularcolumns:: |l|L|L|
2177
2178+----------------+------------------------------+-----------------------+
2179| Name           | Description                  | Features              |
2180+================+==============================+=======================+
2181| bytedesign     | complex classical            | :func:`tracer`, delay,|
2182|                | turtlegraphics pattern       | :func:`update`        |
2183+----------------+------------------------------+-----------------------+
2184| chaos          | graphs Verhulst dynamics,    | world coordinates     |
2185|                | shows that computer's        |                       |
2186|                | computations can generate    |                       |
2187|                | results sometimes against the|                       |
2188|                | common sense expectations    |                       |
2189+----------------+------------------------------+-----------------------+
2190| clock          | analog clock showing time    | turtles as clock's    |
2191|                | of your computer             | hands, ontimer        |
2192+----------------+------------------------------+-----------------------+
2193| colormixer     | experiment with r, g, b      | :func:`ondrag`        |
2194+----------------+------------------------------+-----------------------+
2195| fractalcurves  | Hilbert & Koch curves        | recursion             |
2196+----------------+------------------------------+-----------------------+
2197| lindenmayer    | ethnomathematics             | L-System              |
2198|                | (indian kolams)              |                       |
2199+----------------+------------------------------+-----------------------+
2200| minimal_hanoi  | Towers of Hanoi              | Rectangular Turtles   |
2201|                |                              | as Hanoi discs        |
2202|                |                              | (shape, shapesize)    |
2203+----------------+------------------------------+-----------------------+
2204| paint          | super minimalistic           | :func:`onclick`       |
2205|                | drawing program              |                       |
2206+----------------+------------------------------+-----------------------+
2207| peace          | elementary                   | turtle: appearance    |
2208|                |                              | and animation         |
2209+----------------+------------------------------+-----------------------+
2210| penrose        | aperiodic tiling with        | :func:`stamp`         |
2211|                | kites and darts              |                       |
2212+----------------+------------------------------+-----------------------+
2213| planet_and_moon| simulation of                | compound shapes,      |
2214|                | gravitational system         | :class:`Vec2D`        |
2215+----------------+------------------------------+-----------------------+
2216| tree           | a (graphical) breadth        | :func:`clone`         |
2217|                | first tree (using generators)|                       |
2218+----------------+------------------------------+-----------------------+
2219| wikipedia      | a pattern from the wikipedia | :func:`clone`,        |
2220|                | article on turtle graphics   | :func:`undo`          |
2221+----------------+------------------------------+-----------------------+
2222| yingyang       | another elementary example   | :func:`circle`        |
2223+----------------+------------------------------+-----------------------+
2224
2225Have fun!
2226
2227.. doctest::
2228   :hide:
2229
2230   >>> for turtle in turtles():
2231   ...      turtle.reset()
2232   >>> turtle.penup()
2233   >>> turtle.goto(-200,25)
2234   >>> turtle.pendown()
2235   >>> turtle.write("No one expects the Spanish Inquisition!",
2236   ...      font=("Arial", 20, "normal"))
2237   >>> turtle.penup()
2238   >>> turtle.goto(-100,-50)
2239   >>> turtle.pendown()
2240   >>> turtle.write("Our two chief Turtles are...",
2241   ...      font=("Arial", 16, "normal"))
2242   >>> turtle.penup()
2243   >>> turtle.goto(-450,-75)
2244   >>> turtle.write(str(turtles()))
2245