Source

cpython_sandbox / Doc / library / turtle.rst

Full commit

:mod:`turtle` --- Turtle graphics

Introduction

Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966.

Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.

By combining together these and similar commands, intricate shapes and pictures can easily be drawn.

The :mod:`turtle` module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.

It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.

The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses :mod:`tkinter` for the underlying graphics, it needs a version of Python installed with Tk support.

The object-oriented interface uses essentially two+two classes:

  1. The :class:`TurtleScreen` class defines graphics windows as a playground for the drawing turtles. Its constructor needs a :class:`tkinter.Canvas` or a :class:`ScrolledCanvas` as argument. It should be used when :mod:`turtle` is used as part of some application.

    The function :func:`Screen` returns a singleton object of a :class:`TurtleScreen` subclass. This function should be used when :mod:`turtle` is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible.

    All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface.

  2. :class:`RawTurtle` (alias: :class:`RawPen`) defines Turtle objects which draw on a :class:`TurtleScreen`. Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw.

    Derived from RawTurtle is the subclass :class:`Turtle` (alias: :class:`Pen`), which draws on "the" :class:`Screen` instance which is automatically created, if not already present.

    All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented interface.

The procedural interface provides functions which are derived from the methods of the classes :class:`Screen` and :class:`Turtle`. They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.

To use multiple turtles on a screen one has to use the object-oriented interface.

Note

In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.

Overview of available Turtle and Screen methods

Methods of RawTurtle/Turtle and corresponding functions

Most of the examples in this section refer to a Turtle instance called turtle.

Turtle motion

Tell Turtle's state

Settings for measurement

Pen control

Drawing state

Color control

See also: Screen method :func:`colormode`.

Filling

More drawing control

Turtle state

Visibility

Appearance

Using events

Special Turtle methods

Compound shapes

To use compound turtle shapes, which consist of several polygons of different color, you must use the helper class :class:`Shape` explicitly as described below:

  1. Create an empty Shape object of type "compound".

  2. Add as many components to this object as desired, using the :meth:`addcomponent` method.

    For example:

  3. Now add the Shape to the Screen's shapelist and use it:

Note

The :class:`Shape` class is used internally by the :func:`register_shape` method in different ways. The application programmer has to deal with the Shape class only when using compound shapes like shown above!

Methods of TurtleScreen/Screen and corresponding functions

Most of the examples in this section refer to a TurtleScreen instance called screen.

Window control

Animation control

See also the RawTurtle/Turtle method :func:`speed`.

Using screen events

Input methods

Settings and special methods

Methods specific to Screen, not inherited from TurtleScreen

Public classes

param canvas:a :class:`tkinter.Canvas`, a :class:`ScrolledCanvas` or a :class:`TurtleScreen`

Create a turtle. The turtle has all methods described above as "methods of Turtle/RawTurtle".

Subclass of RawTurtle, has the same interface but draws on a default :class:`Screen` object created automatically when needed for the first time.

param cv:a :class:`tkinter.Canvas`

Provides screen oriented methods like :func:`setbg` etc. that are described above.

Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`.

param master:some Tkinter widget to contain the ScrolledCanvas, i.e. a Tkinter-canvas with scrollbars added

Used by class Screen, which thus automatically provides a ScrolledCanvas as playground for the turtles.

param type_:one of the strings "polygon", "image", "compound"

Data structure modeling shapes. The pair (type_, data) must follow this specification:

type_ data
"polygon" a polygon-tuple, i.e. a tuple of pairs of coordinates
"image" an image (in this form only used internally!)
"compound" None (a compound shape has to be constructed using the :meth:`addcomponent` method)

A two-dimensional vector class, used as a helper class for implementing turtle graphics. May be useful for turtle graphics programs too. Derived from tuple, so a vector is a tuple!

Provides (for a, b vectors, k number):

  • a + b vector addition
  • a - b vector subtraction
  • a * b inner product
  • k * a and a * k multiplication with scalar
  • abs(a) absolute value of a
  • a.rotate(angle) rotation

Help and configuration

How to use help

The public methods of the Screen and Turtle classes are documented extensively via docstrings. So these can be used as online-help via the Python help facilities:

  • When using IDLE, tooltips show the signatures and first lines of the docstrings of typed in function-/method calls.

  • Calling :func:`help` on methods or functions displays the docstrings:

    >>> help(Screen.bgcolor)
    Help on method bgcolor in module turtle:
    
    bgcolor(self, *args) unbound turtle.Screen method
        Set or return backgroundcolor of the TurtleScreen.
    
        Arguments (if given): a color string or three numbers
        in the range 0..colormode or a 3-tuple of such numbers.
    
    
          >>> screen.bgcolor("orange")
          >>> screen.bgcolor()
          "orange"
          >>> screen.bgcolor(0.5,0,0.5)
          >>> screen.bgcolor()
          "#800080"
    
    >>> help(Turtle.penup)
    Help on method penup in module turtle:
    
    penup(self) unbound turtle.Turtle method
        Pull the pen up -- no drawing when moving.
    
        Aliases: penup | pu | up
    
        No argument
    
        >>> turtle.penup()
    
  • The docstrings of the functions which are derived from methods have a modified form:

    >>> help(bgcolor)
    Help on function bgcolor in module turtle:
    
    bgcolor(*args)
        Set or return backgroundcolor of the TurtleScreen.
    
        Arguments (if given): a color string or three numbers
        in the range 0..colormode or a 3-tuple of such numbers.
    
        Example::
    
          >>> bgcolor("orange")
          >>> bgcolor()
          "orange"
          >>> bgcolor(0.5,0,0.5)
          >>> bgcolor()
          "#800080"
    
    >>> help(penup)
    Help on function penup in module turtle:
    
    penup()
        Pull the pen up -- no drawing when moving.
    
        Aliases: penup | pu | up
    
        No argument
    
        Example:
        >>> penup()
    

These modified docstrings are created automatically together with the function definitions that are derived from the methods at import time.

Translation of docstrings into different languages

There is a utility to create a dictionary the keys of which are the method names and the values of which are the docstrings of the public methods of the classes Screen and Turtle.

If you (or your students) want to use :mod:`turtle` with online help in your native language, you have to translate the docstrings and save the resulting file as e.g. :file:`turtle_docstringdict_german.py`.

If you have an appropriate entry in your :file:`turtle.cfg` file this dictionary will be read in at import time and will replace the original English docstrings.

At the time of this writing there are docstring dictionaries in German and in Italian. (Requests please to glingl@aon.at.)

How to configure Screen and Turtles

The built-in default configuration mimics the appearance and behaviour of the old turtle module in order to retain best possible compatibility with it.

If you want to use a different configuration which better reflects the features of this module or which better fits to your needs, e.g. for use in a classroom, you can prepare a configuration file turtle.cfg which will be read at import time and modify the configuration according to its settings.

The built in configuration would correspond to the following turtle.cfg:

width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 400
canvheight = 300
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False

Short explanation of selected entries:

  • The first four lines correspond to the arguments of the :meth:`Screen.setup` method.
  • Line 5 and 6 correspond to the arguments of the method :meth:`Screen.screensize`.
  • shape can be any of the built-in shapes, e.g: arrow, turtle, etc. For more info try help(shape).
  • If you want to use no fillcolor (i.e. make the turtle transparent), you have to write fillcolor = "" (but all nonempty strings must not have quotes in the cfg-file).
  • If you want to reflect the turtle its state, you have to use resizemode = auto.
  • If you set e.g. language = italian the docstringdict :file:`turtle_docstringdict_italian.py` will be loaded at import time (if present on the import path, e.g. in the same directory as :mod:`turtle`.
  • The entries exampleturtle and examplescreen define the names of these objects as they occur in the docstrings. The transformation of method-docstrings to function-docstrings will delete these names from the docstrings.
  • using_IDLE: Set this to True if you regularly work with IDLE and its -n switch ("no subprocess"). This will prevent :func:`exitonclick` to enter the mainloop.

There can be a :file:`turtle.cfg` file in the directory where :mod:`turtle` is stored and an additional one in the current working directory. The latter will override the settings of the first one.

The :file:`Lib/turtledemo` directory contains a :file:`turtle.cfg` file. You can study it as an example and see its effects when running the demos (preferably not from within the demo-viewer).

Demo scripts

There is a set of demo scripts in the :mod:`turtledemo` package. These scripts can be run and viewed using the supplied demo viewer as follows:

python -m turtledemo

Alternatively, you can run the demo scripts individually. For example,

python -m turtledemo.bytedesign

The :mod:`turtledemo` package directory contains:

  • a set of 15 demo scripts demonstrating different features of the new module :mod:`turtle`;
  • a demo viewer :file:`__main__.py` which can be used to view the sourcecode of the scripts and run them at the same time. 14 of the examples can be accessed via the Examples menu; all of them can also be run standalone.
  • The example :mod:`turtledemo.two_canvases` demonstrates the simultaneous use of two canvases with the turtle module. Therefore it only can be run standalone.
  • There is a :file:`turtle.cfg` file in this directory, which serves as an example for how to write and use such files.

The demo scripts are:

Name Description Features
bytedesign complex classical turtle graphics pattern :func:`tracer`, delay, :func:`update`
chaos graphs Verhulst dynamics, shows that computer's computations can generate results sometimes against the common sense expectations world coordinates
clock analog clock showing time of your computer turtles as clock's hands, ontimer
colormixer experiment with r, g, b :func:`ondrag`
fractalcurves Hilbert & Koch curves recursion
lindenmayer ethnomathematics (indian kolams) L-System
minimal_hanoi Towers of Hanoi Rectangular Turtles as Hanoi discs (shape, shapesize)
nim play the classical nim game with three heaps of sticks against the computer. turtles as nimsticks, event driven (mouse, keyboard)
paint super minimalistic drawing program :func:`onclick`
peace elementary turtle: appearance and animation
penrose aperiodic tiling with kites and darts :func:`stamp`
planet_and_moon simulation of gravitational system compound shapes, :class:`Vec2D`
round_dance dancing turtles rotating pairwise in opposite direction compound shapes, clone shapesize, tilt, get_shapepoly, update
tree a (graphical) breadth first tree (using generators) :func:`clone`
wikipedia a pattern from the wikipedia article on turtle graphics :func:`clone`, :func:`undo`
yingyang another elementary example :func:`circle`

Have fun!

Changes since Python 2.6

Changes since Python 3.0