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