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