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