Debian Codegraph @

Doc/library/turtle.rst

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