:mod:`turtle` --- Turtle graphics
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:
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.
: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.
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.
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
- Turtle motion
- Move and draw
- Tell Turtle's state
- Setting and measurement
- Pen control
- Drawing state
- Color control
- More drawing control
- Turtle state
- Using events
- Special Turtle methods
Methods of TurtleScreen/Screen
- Window control
- Animation control
- Using screen events
- Settings and special methods
- Input methods
- Methods specific to Screen
Methods of RawTurtle/Turtle and corresponding functions
Most of the examples in this section refer to a Turtle instance called turtle.
Tell Turtle's state
Settings for measurement
See also: Screen method :func:`colormode`.
More drawing control
Special Turtle methods
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:
Create an empty Shape object of type "compound".
Add as many components to this object as desired, using the :meth:`addcomponent` method.
Now add the Shape to the Screen's shapelist and use it:
Methods of TurtleScreen/Screen and corresponding functions
Most of the examples in this section refer to a TurtleScreen instance called screen.
See also the RawTurtle/Turtle method :func:`speed`.
Using screen events
Settings and special methods
Methods specific to Screen, not inherited from TurtleScreen
|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:
|"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 firstname.lastname@example.org.)
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 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:
|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`|
Changes since Python 2.6
- The methods :meth:`Turtle.tracer`, :meth:`Turtle.window_width` and :meth:`Turtle.window_height` have been eliminated. Methods with these names and functionality are now available only as methods of :class:`Screen`. The functions derived from these remain available. (In fact already in Python 2.6 these methods were merely duplications of the corresponding :class:`TurtleScreen`/:class:`Screen`-methods.)
- The method :meth:`Turtle.fill` has been eliminated. The behaviour of :meth:`begin_fill` and :meth:`end_fill` have changed slightly: now every filling-process must be completed with an end_fill() call.
- A method :meth:`Turtle.filling` has been added. It returns a boolean value: True if a filling process is under way, False otherwise. This behaviour corresponds to a fill() call without arguments in Python 2.6.
Changes since Python 3.0
- The methods :meth:`Turtle.shearfactor`, :meth:`Turtle.shapetransform` and :meth:`Turtle.get_shapepoly` have been added. Thus the full range of regular linear transforms is now available for transforming turtle shapes. :meth:`Turtle.tiltangle` has been enhanced in functionality: it now can be used to get or set the tiltangle. :meth:`Turtle.settiltangle` has been deprecated.
- The method :meth:`Screen.onkeypress` has been added as a complement to :meth:`Screen.onkey` which in fact binds actions to the keyrelease event. Accordingly the latter has got an alias: :meth:`Screen.onkeyrelease`.
- The method :meth:`Screen.mainloop` has been added. So when working only with Screen and Turtle objects one must not additonally import :func:`mainloop` anymore.
- Two input methods has been added :meth:`Screen.textinput` and :meth:`Screen.numinput`. These popup input dialogs and return strings and numbers respectively.
- Two example scripts :file:`tdemo_nim.py` and :file:`tdemo_round_dance.py` have been added to the :file:`Lib/turtledemo` directory.