turtle

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.

—– turtle.py

This module is an extended reimplementation of turtle.py from the Python standard distribution up to Python 2.5. (See: http://www.python.org)

It tries to keep the merits of turtle.py 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.

Roughly it has the following features added:

  • Better animation of the turtle movements, especially of turning the turtle. So the turtles can more easily be used as a visual feedback instrument by the (beginning) programmer.
  • Different turtle shapes, gif-images as turtle shapes, user defined and user controllable turtle shapes, among them compound (multicolored) shapes. Turtle shapes can be stretched and tilted, which makes turtles very versatile geometrical objects.
  • Fine control over turtle movement and screen updates via delay(), and enhanced tracer() and speed() methods.
  • Aliases for the most commonly used commands, like fd for forward etc., following the early Logo traditions. This reduces the boring work of typing long sequences of commands, which often occur in a natural way when kids try to program fancy pictures on their first encounter with turtle graphics.
  • Turtles now have an undo()-method with configurable undo-buffer.
  • Some simple commands/methods for creating event driven programs (mouse-, key-, timer-events). Especially useful for programming games.
  • A scrollable Canvas class. The default scrollable Canvas can be extended interactively as needed while playing around with the turtle(s).
  • A TurtleScreen class with methods controlling background color or background image, window and canvas size and other properties of the TurtleScreen.
  • There is a method, setworldcoordinates(), to install a user defined coordinate-system for the TurtleScreen.
  • The implementation uses a 2-vector class named Vec2D, derived from tuple. This class is public, so it can be imported by the application programmer, which makes certain types of computations very natural and compact.
  • Appearance of the TurtleScreen and the Turtles at startup/import can be configured by means of a turtle.cfg configuration file. The default configuration mimics the appearance of the old turtle module.
  • If configured appropriately the module reads in docstrings from a docstring dictionary in some different language, supplied separately and replaces the English ones by those read in. There is a utility function write_docstringdict() to write a dictionary with the original (English) docstrings to disc, so it can serve as a template for translations.

Behind the scenes there are some features included with possible extensions in mind. These will be commented and documented elsewhere.

Functions

Screen() Return the singleton screen object.
acos(x) Return the arc cosine (measured in radians) of x.
acosh(x) Return the inverse hyperbolic cosine of x.
addshape(name[, shape]) Adds a turtle shape to TurtleScreen’s shapelist.
asin(x) Return the arc sine (measured in radians) of x.
asinh(x) Return the inverse hyperbolic sine of x.
atan(x) Return the arc tangent (measured in radians) of x.
atan2(y, x) Return the arc tangent (measured in radians) of y/x.
atanh(x) Return the inverse hyperbolic tangent of x.
back(distance) Move the turtle backward by distance.
backward(distance) Move the turtle backward by distance.
begin_fill() Called just before drawing a shape to be filled.
begin_poly() Start recording the vertices of a polygon.
bgcolor(*args) Set or return backgroundcolor of the TurtleScreen.
bgpic([picname]) Set background image or return name of current backgroundimage.
bk(distance) Move the turtle backward by distance.
bye() Shut the turtlegraphics window.
ceil(x) Return the ceiling of x as a float.
circle(radius[, extent, steps]) Draw a circle with given radius.
clear() Delete the turtle’s drawings from the screen.
clearscreen() Delete all drawings and all turtles from the TurtleScreen.
clearstamp(stampid) Delete stamp with given stampid
clearstamps([n]) Delete all or first/last n of turtle’s stamps.
clone() Create and return a clone of the
color(*args) Return or set the pencolor and fillcolor.
colormode([cmode]) Return the colormode or set it to 1.0 or 255.
config_dict(filename) Convert content of config-file into dictionary.
copysign(x, y) Return x with the sign of y.
cos(x) Return the cosine of x (measured in radians).
cosh(x) Return the hyperbolic cosine of x.
deepcopy(x[, memo, _nil]) Deep copy operation on arbitrary Python objects.
degrees([fullcircle]) Set angle measurement units to degrees.
delay([delay]) Return or set the drawing delay in milliseconds.
distance(x[, y]) Return the distance from the turtle to (x,y) in turtle step units.
done([n]) Run the main loop of Tcl.
dot([size]) Draw a dot with diameter size, using color.
down() Pull the pen down – drawing when moving.
end_fill() Fill the shape drawn after the call begin_fill().
end_poly() Stop recording the vertices of a polygon.
erf(x) Error function at x.
erfc(x) Complementary error function at x.
exitonclick() Go into mainloop until the mouse is clicked.
exp(x) Return e raised to the power of x.
expm1(x) Return exp(x)-1.
fabs(x) Return the absolute value of the float x.
factorial((x) -> Integral) Find x!.
fd(distance) Move the turtle forward by the specified distance.
fill([flag]) Call fill(True) before drawing a shape to fill, fill(False) when done.
fillcolor(*args) Return or set the fillcolor.
floor(x) Return the floor of x as a float.
fmod(x, y) Return fmod(x, y), according to platform C.
forward(distance) Move the turtle forward by the specified distance.
frexp(x) Return the mantissa and exponent of x, as pair (m, e).
fsum(iterable) Return an accurate floating point sum of values in the iterable.
gamma(x) Gamma function at x.
get_poly() Return the lastly recorded polygon.
getcanvas() Return the Canvas of this TurtleScreen.
getmethparlist(ob) Get strings describing the arguments for the given object
getpen() Return the Turtleobject itself.
getscreen() Return the TurtleScreen object, the turtle is drawing on.
getshapes() Return a list of names of all currently available turtle shapes.
getturtle() Return the Turtleobject itself.
goto(x[, y]) Move turtle to an absolute position.
heading() Return the turtle’s current heading.
hideturtle() Makes the turtle invisible.
home() Move turtle to the origin - coordinates (0,0).
ht() Makes the turtle invisible.
hypot(x, y) Return the Euclidean distance, sqrt(x*x + y*y).
isdown() Return True if pen is down, False if it’s up.
isfile(path) Test whether a path is a regular file
isinf((x) -> bool) Check if float x is infinite (positive or negative).
isnan((x) -> bool) Check if float x is not a number (NaN).
isvisible() Return True if the Turtle is shown, False if it’s hidden.
join(a, *p) Join two or more pathname components, inserting ‘/’ as needed.
ldexp(x, i) Return x * (2**i).
left(angle) Turn turtle left by angle units.
lgamma(x) Natural logarithm of absolute value of Gamma function at x.
listen([xdummy, ydummy]) Set focus on TurtleScreen (in order to collect key-events)
log(x[, base]) Return the logarithm of x to the given base.
log10(x) Return the base 10 logarithm of x.
log1p(x) Return the natural logarithm of 1+x (base e).
lt(angle) Turn turtle left by angle units.
mainloop([n]) Run the main loop of Tcl.
mode([mode]) Set turtle-mode (‘standard’, ‘logo’ or ‘world’) and perform reset.
modf(x) Return the fractional and integer parts of x.
onclick(fun[, btn, add]) Bind fun to mouse-click event on this turtle on canvas.
ondrag(fun[, btn, add]) Bind fun to mouse-move event on this turtle on canvas.
onkey(fun, key) Bind fun to key-release event of key.
onrelease(fun[, btn, add]) Bind fun to mouse-button-release event on this turtle on canvas.
onscreenclick(fun[, btn, add]) Bind fun to mouse-click event on canvas.
ontimer(fun[, t]) Install a timer, which calls fun after t milliseconds.
pd() Pull the pen down – drawing when moving.
pen([pen]) Return or set the pen’s attributes.
pencolor(*args) Return or set the pencolor.
pendown() Pull the pen down – drawing when moving.
pensize([width]) Set or return the line thickness.
penup() Pull the pen up – no drawing when moving.
pos() Return the turtle’s current location (x,y), as a Vec2D-vector.
position() Return the turtle’s current location (x,y), as a Vec2D-vector.
pow(x, y) Return x**y (x to the power of y).
pu() Pull the pen up – no drawing when moving.
radians() Set the angle measurement units to radians.
read_docstrings(lang) Read in docstrings from lang-specific docstring dictionary.
readconfig(cfgdict) Read config-files, change configuration-dict accordingly.
register_shape(name[, shape]) Adds a turtle shape to TurtleScreen’s shapelist.
reset() Delete the turtle’s drawings and restore its default values.
resetscreen() Reset all Turtles on the Screen to their initial state.
resizemode([rmode]) Set resizemode to one of the values: “auto”, “user”, “noresize”.
right(angle) Turn turtle right by angle units.
rt(angle) Turn turtle right by angle units.
screensize([canvwidth, canvheight, bg]) Resize the canvas the turtles are drawing on.
seth(to_angle) Set the orientation of the turtle to to_angle.
setheading(to_angle) Set the orientation of the turtle to to_angle.
setpos(x[, y]) Move turtle to an absolute position.
setposition(x[, y]) Move turtle to an absolute position.
settiltangle(angle) Rotate the turtleshape to point in the specified direction
setundobuffer(size) Set or disable undobuffer.
setup([width, height, startx, starty]) Set the size and position of the main window.
setworldcoordinates(llx, lly, urx, ury) Set up a user defined coordinate-system.
setx(x) Set the turtle’s first coordinate to x
sety(y) Set the turtle’s second coordinate to y
shape([name]) Set turtle shape to shape with given name / return current shapename.
shapesize([stretch_wid, stretch_len, outline]) Set/return turtle’s stretchfactors/outline.
showturtle() Makes the turtle visible.
sin(x) Return the sine of x (measured in radians).
sinh(x) Return the hyperbolic sine of x.
speed([speed]) Return or set the turtle’s speed.
split(p) Split a pathname.
sqrt(x) Return the square root of x.
st() Makes the turtle visible.
stamp() Stamp a copy of the turtleshape onto the canvas and return its id.
tan(x) Return the tangent of x (measured in radians).
tanh(x) Return the hyperbolic tangent of x.
tilt(angle) Rotate the turtleshape by angle.
tiltangle() Return the current tilt-angle.
title(titlestring) Set title of turtle-window
towards(x[, y]) Return the angle of the line from the turtle’s position to (x, y).
tracer([flag, delay]) Turns turtle animation on/off and set delay for update drawings.
trunc((x:Real) -> Integral) Truncates x to the nearest Integral toward 0.
turtles() Return the list of turtles on the
turtlesize([stretch_wid, stretch_len, outline]) Set/return turtle’s stretchfactors/outline.
undo() undo (repeatedly) the last turtle action.
undobufferentries() Return count of entries in the undobuffer.
up() Pull the pen up – no drawing when moving.
update() Perform a TurtleScreen update.
width([width]) Set or return the line thickness.
window_height() Return the height of the turtle window.
window_width() Returns the width of the turtle window.
write(arg[, move, align, font]) Write text at the current turtle position.
write_docstringdict([filename]) Create and write docstring-dictionary to file.
xcor() Return the turtle’s x coordinate.
ycor() Return the turtle’s y coordinate — No arguments.

Classes

Canvas([master, cnf]) Canvas widget to display graphical elements like lines or text.
Pen alias of Turtle
RawPen alias of RawTurtle
RawTurtle([canvas, shape, undobuffersize, ...]) Animation part of the RawTurtle.
ScrolledCanvas(master[, width, height, ...]) Modeled after the scrolled canvas class from Grayons’s Tkinter book.
Shape(type_[, data]) Data structure modeling shapes.
TNavigator([mode]) Navigation part of the RawTurtle.
TPen([resizemode]) Drawing part of the RawTurtle.
Tbuffer([bufsize]) Ring buffer used as undobuffer for RawTurtle objects.
Turtle([shape, undobuffersize, visible]) RawTurtle auto-creating (scrolled) canvas.
TurtleScreen(cv[, mode, colormode, delay]) Provides screen oriented methods like setbg etc.
TurtleScreenBase(cv) Provide the basic graphics functionality.
Vec2D A 2 dimensional vector class, used as a helper class for implementing turtle graphics.

Exceptions

Terminator Will be raised in TurtleScreen.update, if _RUNNING becomes False.
TurtleGraphicsError Some TurtleGraphics Error