turtle — Turtle graphics

Código fuente: Lib/turtle.py


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.

Turtle graphics is an implementation of the drawing tools introduced in Logo in 1967. It was created as an educational tool, and its instant, visible feedback makes it an effective way for learners to encounter programming concepts. It is also a convenient way to produce simple graphical output without bringing in external libraries.

This document includes four main sections:

  • Tutorial teaches the basics of turtle drawing.

  • Reference describes the functions, methods and classes this module defines.

  • How-to guides detail how to handle specific tasks.

  • Explicación provides background on the object-oriented interface.

Nota

Turtle graphics requires the tkinter optional module. The python.org installers for Windows and macOS include it, but some Linux distributions and other platforms may package it separately. If import turtle fails with an error mentioning _tkinter, look for documentation from your distributor (that is, whoever provided Python to you). Check this in advance if you’re planning to use turtle graphics with a learner.

Tutorial

Los nuevos usuarios deberían empezar aquí. En este tutorial, exploraremos algunos de los conceptos básicos del dibujo de tortugas.

Iniciando un entorno para tortugas

En un shell de Python, importe todos los objetos del módulo turtle:

from turtle import *

If you run into a Standard library module '_tkinter' was not found error, you’ll have to install the Tk interface package on your system.

Nothing appears yet. To open the turtle window, make the turtle visible:

showturtle()

A new window opens, with the turtle in the middle, shown as an arrow heading East.

Dibujo básico

Envía la tortuga hacia adelante 100 pasos:

forward(100)

You should see a line drawn by the turtle, heading East. Change the direction of the turtle, so that it turns 120 degrees left (anti-clockwise):

left(120)

Continuemos dibujando un triángulo:

forward(100)
left(120)
forward(100)

Observa cómo la tortuga, representada por una flecha, apunta en diferentes direcciones a medida que la diriges.

Experiment with those commands, and also with backward() and right(). Many commands also have shorter aliases, such as fd() for forward().

Control del lápiz

Intente cambiar el color (por ejemplo, color('blue')) y el ancho de la línea (por ejemplo, width(3)) y luego vuelva a dibujar.

También puedes mover la tortuga sin dibujar, levantando el lápiz: up() antes de moverla. Para comenzar a dibujar nuevamente, usa down().

La posición de la tortuga

Envía a tu tortuga de regreso a su punto de partida (útil si ha desaparecido de la pantalla):

home()

La posición inicial está en el centro de la pantalla de la tortuga. Si alguna vez necesitas saberlas, obtén las coordenadas x-y de la tortuga con:

pos()

El hogar está en (0, 0).

Y después de un tiempo, probablemente ayudará a limpiar la ventana para que podamos comenzar de nuevo:

clearscreen()

Creando patrones algorítmicos

Utilizando bucles, es posible construir patrones geométricos:

for steps in range(100):
    for c in ('blue', 'red', 'green'):
        color(c)
        forward(steps)
        right(30)

- ¡que, por supuesto, están limitadas únicamente por la imaginación!

Dibujemos la forma de estrella en la parte superior de esta página. Queremos líneas rojas, rellenas con amarillo:

color('red')
fillcolor('yellow')

Así como up() y down() determinan si se dibujarán líneas, el relleno se puede activar y desactivar:

begin_fill()

A continuación crearemos un bucle:

start = pos()

while True:
    forward(200)
    left(170)
    if distance(start) < 1:
        break

distance(start) < 1 is a good way to know when the turtle is back at its start position.

Por último, completa el relleno:

end_fill()

(Tenga en cuenta que el llenado solo se realiza cuando se da el comando end_fill()).

Reference

Turtle methods and functions

Casi todos los ejemplos de esta sección se refieren a una instancia Turtle llamada turtle.

Mover y dibujar

turtle.forward(distance)
turtle.fd(distance)
Parámetros:

distance – un número

Mover hacia adelante la tortuga la ditance especificada, en la dirección en la que la tortuga apunta.

>>> turtle.position()
(0.00,0.00)
>>> turtle.forward(25)
>>> turtle.position()
(25.00,0.00)
>>> turtle.forward(-75)
>>> turtle.position()
(-50.00,0.00)
turtle.back(distance)
turtle.bk(distance)
turtle.backward(distance)
Parámetros:

distance – un número

Move the turtle backward by distance, opposite to the direction the turtle is headed. The turtle’s heading does not change.

>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
turtle.right(angle)
turtle.rt(angle)
Parámetros:

angle – un número

Turn the turtle right by the specified angle. The angle is measured in degrees by default; the unit can be changed with degrees() or radians(). How the heading is measured depends on the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
turtle.left(angle)
turtle.lt(angle)
Parámetros:

angle – un número

Turn the turtle left by the specified angle. The angle is measured in degrees by default; the unit can be changed with degrees() or radians(). How the heading is measured depends on the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.left(45)
>>> turtle.heading()
67.0
turtle.goto(x, y=None)
turtle.setpos(x, y=None)
turtle.setposition(x, y=None)
Parámetros:
  • x – un número o un par/vector de números

  • y – un número o None

Move the turtle to an absolute position. If y is None, x must be a pair of coordinates or a Vec2D, for example as returned by pos(). If the pen is down, a line is drawn. The turtle’s heading does not change.

>>> tp = turtle.pos()
>>> tp
(0.00,0.00)
>>> turtle.goto(60,30)
>>> turtle.pos()
(60.00,30.00)
>>> turtle.goto((20,80))
>>> turtle.pos()
(20.00,80.00)
>>> turtle.goto(tp)
>>> turtle.pos()
(0.00,0.00)
turtle.teleport(x=None, y=None, *, fill_gap=False)
Parámetros:
  • x – un número o None

  • y – un número o None

  • fill_gap – un booleano

Teleport, or instantly move, the turtle to an absolute position. Unlike goto(), no line is drawn. If x or y is not given, that coordinate is kept as it is. The turtle’s heading does not change.

If the turtle is filling a shape, the shape drawn so far is finished and filled before teleporting, and filling starts again at the new position. Pass fill_gap=True to keep filling one shape instead. The teleport then counts as an edge of the shape, as it would with goto().

>>> tp = turtle.pos()
>>> tp
(0.00,0.00)
>>> turtle.teleport(60)
>>> turtle.pos()
(60.00,0.00)
>>> turtle.teleport(y=10)
>>> turtle.pos()
(60.00,10.00)
>>> turtle.teleport(20, 30)
>>> turtle.pos()
(20.00,30.00)

Added in version 3.12.

turtle.setx(x)
Parámetros:

x – un número

Set the turtle’s x coordinate to x. The y coordinate is unchanged.

>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)
turtle.sety(y)
Parámetros:

y – un número

Set the turtle’s y coordinate to y. The x coordinate is unchanged.

>>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)
turtle.setheading(to_angle)
turtle.seth(to_angle)
Parámetros:

to_angle – un número

Set the turtle’s heading to to_angle. Here are some common directions in degrees:

modo estándar

modo logo

0 - este

0 - norte

90 - norte

90 - este

180 - oeste

180 - sur

270 - sur

270 - oeste

>>> turtle.setheading(90)
>>> turtle.heading()
90.0
turtle.home()

Move the turtle to the origin, coordinates (0,0). The turtle’s heading is set to its start orientation, which depends on the turtle mode, see mode().

>>> turtle.heading()
90.0
>>> turtle.position()
(0.00,-10.00)
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
turtle.circle(radius, extent=None, steps=None)
Parámetros:
  • radius – un número

  • extent – un número o None

  • steps – un entero o None

Draw a circle with the given radius. The center is radius units left of the turtle; extent, an angle, determines which part of the circle is drawn. If extent is not given, draw the entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position. Draw the arc in the counterclockwise direction if radius is positive, otherwise in the clockwise direction. Finally, the turtle’s heading is changed by extent.

As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. If not given, it will be calculated automatically. May be used to draw regular polygons.

>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(50)
>>> turtle.position()
(-0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(120, 180)  # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0
turtle.dot()
turtle.dot(size)
turtle.dot(color, /)
turtle.dot(size, color, /)
turtle.dot(size, r, g, b, /)
Parámetros:
  • size – a positive integer or None

  • color – un colorstring o una tupla numérica de color

Draw a circular dot with diameter size, using color. If size is not given, the larger of pensize + 4 and 2 * pensize is used. If color is not given, the current pencolor is used.

>>> turtle.home()
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
>>> turtle.position()
(100.00,-0.00)
>>> turtle.heading()
0.0
turtle.stamp()

Stamp a copy of the turtle shape onto the canvas and return its id. The stamp is placed at the current turtle position. The returned id can be used to delete the stamp with clearstamp().

>>> turtle.color("blue")
>>> stamp_id = turtle.stamp()
>>> turtle.fd(50)
turtle.clearstamp(stampid)
Parámetros:

stampid – an integer

Delete the stamp with the given stampid. stampid must be the return value of a previous stamp() call.

>>> turtle.position()
(150.00,-0.00)
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.position()
(200.00,-0.00)
>>> turtle.clearstamp(astamp)
>>> turtle.position()
(200.00,-0.00)
turtle.clearstamps(n=None)
Parámetros:

n – un entero o None

Delete all or the first or last n of the turtle’s stamps. If n is not given, delete all stamps. If n is positive, delete the first n stamps. If n is negative, delete the last n stamps, so -2 deletes the last two.

>>> for i in range(8):
...     unused_stamp_id = turtle.stamp()
...     turtle.fd(30)
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()
turtle.undo()

Undo the last turtle action. Calling undo() repeatedly undoes one action at a time. The number of actions that can be undone is set by the size of the undo buffer, see setundobuffer().

>>> for i in range(4):
...     turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
...     turtle.undo()
turtle.speed(speed=None)
Parámetros:

speed – an integer, a string or None

Return or set the turtle’s speed. If speed is not given, return the current speed. Otherwise set the turtle’s speed to an integer from 0 to 10. A number above 0.5 and below 10.5 is rounded to the nearest integer. Any other number sets the speed to 0. You can also use these names instead of numbers:

  • «fastest»: 0

  • «fast»: 10

  • «normal»: 6

  • «slow»: 3

  • «slowest»: 1

Speeds from 1 to 10 give increasingly faster animation of line drawing and turtle turning. A speed of 0 means that no animation takes place: forward() and back() make the turtle jump, and likewise left() and right() make the turtle turn instantly.

>>> turtle.speed()
3
>>> turtle.speed('normal')
>>> turtle.speed()
6
>>> turtle.speed(9)
>>> turtle.speed()
9

Mostrar el estado de la tortuga

turtle.position()
turtle.pos()

Return the turtle’s current location (x,y) as a Vec2D vector.

>>> turtle.pos()
(440.00,-0.00)
turtle.towards(x, y=None)
Parámetros:
  • x – un número o par de vectores numéricos o una instancia de la tortuga

  • y – un número si x es un número, si no None

Return the angle of the line from the turtle’s position to (x,y). If y is None, x must be a pair of coordinates, a Vec2D, for example as returned by pos(), or another turtle. The angle is measured from the turtle’s start orientation, which depends on the turtle mode, see mode().

>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
225.0
turtle.xcor()

Devuelve la coordinada x de la tortuga.

>>> turtle.home()
>>> turtle.left(50)
>>> turtle.forward(100)
>>> turtle.pos()
(64.28,76.60)
>>> print(round(turtle.xcor(), 5))
64.27876
turtle.ycor()

Devuelve la coordenada y de la tortuga.

>>> turtle.home()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print(turtle.pos())
(50.00,86.60)
>>> print(round(turtle.ycor(), 5))
86.60254
turtle.heading()

Return the turtle’s current heading. The value depends on the turtle mode, see mode().

>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0
turtle.distance(x, y=None)
Parámetros:
  • x – un número o par de vectores numéricos o una instancia de la tortuga

  • y – un número si x es un número, si no None

Return the distance from the turtle to (x,y) in turtle step units. If y is None, x must be a pair of coordinates, a Vec2D, for example as returned by pos(), or another turtle.

>>> turtle.home()
>>> turtle.distance(30,40)
50.0
>>> turtle.distance((30,40))
50.0
>>> joe = Turtle()
>>> joe.forward(77)
>>> turtle.distance(joe)
77.0

Configuración de las medidas

turtle.degrees(fullcircle=360.0)
Parámetros:

fullcircle – un número

Set the angle measurement units to degrees. The number of degrees in a full circle is set to fullcircle, which defaults to 360.

>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0

>>> # Change angle measurement unit to grad (also known as gon,
>>> # grade, or gradian and equals 1/100-th of the right angle.)
>>> turtle.degrees(400.0)
>>> turtle.heading()
100.0
>>> turtle.degrees(360)
>>> turtle.heading()
90.0
turtle.radians()

Set the angle measurement units to radians. Equivalent to degrees(2 * math.pi).

>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0
>>> turtle.radians()
>>> turtle.heading()
1.5707963267948966

Control del lápiz

Estado de dibujo
turtle.pendown()
turtle.pd()
turtle.down()

Lower the pen. The turtle draws a line when it moves.

turtle.penup()
turtle.pu()
turtle.up()

Lift the pen. The turtle does not draw when it moves.

turtle.pensize(width=None)
turtle.width(width=None)
Parámetros:

width – a positive number or None

Return or set the line thickness. If width is not given, return the current pensize. If resizemode is set to «auto» and the turtle shape is a polygon, that polygon is drawn with the same line thickness.

>>> turtle.pensize()
1
>>> turtle.pensize(10)   # de aquí en adelante se dibujan líneas con ancho 10
turtle.pen(pen=None, **pendict)
Parámetros:
  • pen – a dictionary or None

  • pendict – keyword arguments with the keys below

Return or set the pen’s attributes. The attributes are returned as a dictionary with the following keys and values:

  • «shown»: True or False

  • «pendown»: True or False

  • «pencolor»: a color string or a color tuple

  • «fillcolor»: a color string or a color tuple

  • «pensize»: a positive number

  • «speed»: a number from 0 to 10

  • «resizemode»: «auto», «user» or «noresize»

  • «stretchfactor»: a pair of positive numbers

  • «shearfactor»: a number

  • «outline»: a positive number

  • «tilt»: a number

Such a dictionary can be passed as pen to restore a former pen state. The attributes can also be given as keyword arguments, which can be used to set several of them in one statement.

>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> turtle.pen()
{'shown': True, 'pendown': True, 'pencolor': 'red', 'fillcolor': 'black',
 'pensize': 10, 'speed': 9, 'resizemode': 'noresize',
 'stretchfactor': (1.0, 1.0), 'shearfactor': 0.0, 'outline': 1,
 'tilt': 0.0}
>>> penstate = turtle.pen()
>>> turtle.color("yellow", "")
>>> turtle.penup()
>>> turtle.pen()["pencolor"]
'yellow'
>>> # restore the saved pen state, but with a green fill
>>> turtle.pen(penstate, fillcolor="green")
>>> turtle.pen()["pencolor"]
'red'
>>> turtle.pen()["fillcolor"]
'green'
turtle.isdown()

Return True if the pen is down, False if it’s up.

>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True
Control del color
turtle.pencolor()
turtle.pencolor(color, /)
turtle.pencolor(r, g, b, /)

Devuelve o establece el color del lápiz.

Se permiten cuatro formatos de entrada:

pencolor()

Return the current pencolor as color specification string or as a tuple (see example). May be used as input to another color(), pencolor(), fillcolor() or bgcolor() call.

pencolor(colorstring)

Set the pencolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c".

pencolor((r, g, b))

Set the pencolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be between 0 and colormode, where colormode is either 1.0 or 255 (see colormode()).

pencolor(r, g, b)

Set the pencolor to the RGB color represented by r, g, and b. Each of r, g, and b must be between 0 and colormode.

If the turtle shape is a polygon, the outline of that polygon is drawn with the newly set pencolor.

>>> colormode()
1.0
>>> turtle.pencolor()
'red'
>>> turtle.pencolor("brown")
>>> turtle.pencolor()
'brown'
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
(0.2, 0.8, 0.5490196078431373)
>>> colormode(255)
>>> turtle.pencolor()
(51.0, 204.0, 140.0)
>>> turtle.pencolor('#32c18f')
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
turtle.fillcolor()
turtle.fillcolor(color, /)
turtle.fillcolor(r, g, b, /)

Return or set the fillcolor.

Se permiten cuatro formatos de entrada:

fillcolor()

Return the current fillcolor as color specification string, possibly in tuple format (see example). May be used as input to another color(), pencolor(), fillcolor() or bgcolor() call.

fillcolor(colorstring)

Set the fillcolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c".

fillcolor((r, g, b))

Set the fillcolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be between 0 and colormode, where colormode is either 1.0 or 255 (see colormode()).

fillcolor(r, g, b)

Set the fillcolor to the RGB color represented by r, g, and b. Each of r, g, and b must be between 0 and colormode.

If the turtle shape is a polygon, the interior of that polygon is drawn with the newly set fillcolor.

>>> turtle.fillcolor("violet")
>>> turtle.fillcolor()
'violet'
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor((50, 193, 143))  # Integers, not floats
>>> turtle.fillcolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor('#ffffff')
>>> turtle.fillcolor()
(255.0, 255.0, 255.0)
turtle.color()
turtle.color(color, /)
turtle.color(r, g, b, /)
turtle.color(pencolor, fillcolor, /)

Return or set the pencolor and fillcolor.

Several input formats are allowed. They use 0 to 3 arguments as follows:

color()

Devuelve el valor actual de pencolor y el valor actual de fillcolor como un par de colores especificados como palabras o tuplas, como devuelven las funciones pencolor() y fillcolor().

color(colorstring), color((r,g,b)), color(r,g,b)

Inputs as in pencolor(). Set both the pencolor and the fillcolor to the given value.

color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2))

Equivalente a pencolor(colorstring1) y fillcolor(colorstring2) y análogamente si se usa el otro formato de entrada.

If the turtle shape is a polygon, the outline and interior of that polygon are drawn with the newly set colors.

>>> turtle.color("red", "green")
>>> turtle.color()
('red', 'green')
>>> color("#285078", "#a0c8f0")
>>> color()
((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))

Ver también: Método Screeen colormode().

Relleno
turtle.filling()

Return True if the turtle is filling, False otherwise.

>>> turtle.begin_fill()
>>> if turtle.filling():
...    turtle.pensize(5)
... else:
...    turtle.pensize(3)
turtle.fill()

Fill the shape drawn in the with block.

>>> turtle.color("black", "red")
>>> with turtle.fill():
...     turtle.circle(80)

fill() is a context manager, so using it is the same as calling begin_fill() before the block and end_fill() after it:

>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()

Added in version 3.14.

turtle.begin_fill()

Call just before drawing a shape to be filled. The shape is filled by the next call to end_fill().

turtle.end_fill()

Rellena la forma dibujada después de última llamada a la función begin_fill().

If the shape crosses itself or several shapes overlap, whether the overlapping parts are filled depends on the operating system, the type of overlap and how many there are. For example, the turtle star above may be either all yellow or have some white regions.

>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()
Más controles de dibujo
turtle.reset()

Delete the turtle’s drawings and re-center the turtle. The turtle’s settings are restored to their default values.

>>> turtle.goto(0,-22)
>>> turtle.left(100)
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
turtle.clear()

Delete the turtle’s drawings from the screen. The state and position of the turtle as well as the drawings of other turtles are not affected.

turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))
Parámetros:
  • arg – an object

  • move – un booleano

  • align – a string

  • font – a tuple of a string, an integer and a string

Write text at the current turtle position. The text is the string representation of arg. align is one of the strings «left», «center» or «right» and says how the text is placed relative to the turtle position. font is a triple of font name, font size and font type. If move is True, the pen is moved to the bottom-right corner of the text.

>>> turtle.write("Home = ", True, align="center")
>>> turtle.write((0,0), True)

Estado de la Tortuga

Visibilidad
turtle.hideturtle()
turtle.ht()

Make the turtle invisible. If the pen is down, movement still draws.

turtle.showturtle()
turtle.st()

Hace visible la tortuga.

turtle.isvisible()

Return True if the turtle is visible, False if it’s hidden.

>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
True
Apariencia
turtle.shape(name=None)
Parámetros:

name – a string or None

Set the turtle shape to the named shape. If name is not given, return the name of the current shape. The shape must exist in the TurtleScreen’s shape list. Initially there are the following shapes: «arrow», «turtle», «circle», «square», «triangle» and «classic». To add shapes, see the Screen method register_shape().

>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'
turtle.resizemode(rmode=None)
Parámetros:

rmode – a string or None

Set the resizemode to «auto», «user» or «noresize». If rmode is not given, return the current resizemode. The different resizemodes have the following effects:

  • «auto»: the turtle is resized according to the value of pensize().

  • «user»: the turtle is resized according to the stretch factors and outline width, which are set by shapesize().

  • «noresize»: the turtle is not resized.

resizemode("user") es llamado por la función shapesize() cuando se usa con argumentos.

>>> turtle.resizemode()
'noresize'
>>> turtle.resizemode("auto")
>>> turtle.resizemode()
'auto'
turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None)
turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)
Parámetros:
  • stretch_wid – a positive number or None

  • stretch_len – a positive number or None

  • outline – a positive number or None

Return or set the turtle’s stretch factors and outline width. If no arguments are given, return the current values. Otherwise set resizemode to «user», so that the turtle is displayed stretched according to its stretch factors:

  • stretch_wid: the stretch factor perpendicular to the turtle’s heading

  • stretch_len: the stretch factor in the direction of the turtle’s heading

  • outline: the width of the shape’s outline

For example, shapesize(2, 1) makes the turtle twice as wide without changing its length. If only stretch_wid is given, stretch_len is set to the same value.

>>> turtle.shapesize()
(1.0, 1.0, 1)
>>> turtle.resizemode("user")
>>> turtle.shapesize(5, 5, 12)
>>> turtle.shapesize()
(5, 5, 12)
>>> turtle.shapesize(outline=8)
>>> turtle.shapesize()
(5, 5, 8)
turtle.shearfactor(shear=None)
Parámetros:

shear – un número o None

Return or set the current shear factor. Shearing slants the turtle shape, like the slant of italic letters. The shear factor says how much it is slanted: 0 is not slanted at all, and the larger the number, the stronger the slant. Negative numbers slant the other way. If shear is not given, return the current shear factor. Otherwise slant the turtle shape accordingly and set resizemode to «user». The turtle’s heading does not change. Precisely, the shear factor is the tangent of the shear angle.

>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.shearfactor(0.5)
>>> turtle.shearfactor()
0.5
turtle.tilt(angle)
Parámetros:

angle – un número

Turn the turtle shape by angle from its current tilt angle. The turtle’s heading does not change, so the turtle keeps moving in the same direction. See tiltangle().

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(30)
>>> turtle.fd(50)
>>> turtle.tilt(30)
>>> turtle.fd(50)
turtle.tiltangle(angle=None)
Parámetros:

angle – un número o None

Return or set the current tilt angle. The tilt angle is the angle between the direction the turtle shape points in and the direction the turtle moves in. Normally the shape points in the direction of movement, so the tilt angle is 0. If angle is given, turn the turtle shape to that tilt angle, no matter what it was before, and set resizemode to «user». The turtle’s heading does not change. If angle is not given, return the current tilt angle.

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(45)
>>> turtle.tiltangle()
45.0
turtle.shapetransform(t11=None, t12=None, t21=None, t22=None)
Parámetros:
  • t11 – un número o None

  • t12 – un número o None

  • t21 – un número o None

  • t22 – un número o None

Return or set the transformation matrix of the turtle shape. The matrix combines the stretch factors, the shear factor and the tilt angle of the turtle shape into four numbers: t11 and t12 form its first row, t21 and t22 its second. If none of them are given, return the current matrix as a tuple of four numbers. Otherwise set the given elements and update the stretch factors, shear factor and tilt angle accordingly. t11 * t22 - t12 * t21 must not be zero, otherwise an error is raised.

>>> turtle = Turtle()
>>> turtle.shape("square")
>>> turtle.shapesize(4,2)
>>> turtle.shearfactor(-0.5)
>>> turtle.shapetransform()
(4.0, -1.0, -0.0, 2.0)
turtle.get_shapepoly()

Return the points that form the outline of the current turtle shape as a tuple of (x, y) coordinate pairs. These points can be used to define a new shape or parts of a compound shape.

>>> turtle.shape("square")
>>> turtle.shapetransform(4, -1, 0, 2)
>>> turtle.get_shapepoly()
((50, -20), (30, 20), (-50, 20), (-30, -20))

Usando eventos

turtle.onclick(fun, btn=1, add=None)
Parámetros:
  • fun – a function with two arguments or None

  • btn – an integer

  • add – a boolean or None

Bind fun to mouse-click events on this turtle. fun is called with the coordinates of the clicked point on the canvas. If fun is None, existing bindings are removed. btn is the number of the mouse button and defaults to 1, the left mouse button. If add is True, a new binding is added, otherwise it replaces a previous binding. Example for the anonymous turtle, that is, the procedural way:

>>> def turn(x, y):
...     left(180)
...
>>> onclick(turn)  # Now clicking into the turtle will turn it.
>>> onclick(None)  # event-binding will be removed
turtle.onrelease(fun, btn=1, add=None)
Parámetros:
  • fun – a function with two arguments or None

  • btn – an integer

  • add – a boolean or None

Bind fun to mouse-button-release events on this turtle. fun is called with the coordinates of the point on the canvas where the mouse button is released. If fun is None, existing bindings are removed. btn is the number of the mouse button and defaults to 1, the left mouse button. If add is True, a new binding is added, otherwise it replaces a previous binding.

>>> class MyTurtle(Turtle):
...     def glow(self,x,y):
...         self.fillcolor("red")
...
...     def unglow(self,x,y):
...         self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
turtle.ondrag(fun, btn=1, add=None)
Parámetros:
  • fun – a function with two arguments or None

  • btn – an integer

  • add – a boolean or None

Bind fun to mouse-move events on this turtle. fun is called with the coordinates of the mouse pointer on the canvas. If fun is None, existing bindings are removed. btn is the number of the mouse button and defaults to 1, the left mouse button. If add is True, a new binding is added, otherwise it replaces a previous binding. Every sequence of mouse-move events on a turtle is preceded by a mouse-click event on that turtle.

>>> turtle.ondrag(turtle.goto)

Clicking and dragging the turtle then moves it across the screen, drawing by hand if the pen is down.

Métodos especiales de Turtle

turtle.poly()

Record the vertices of a polygon drawn in the with block. The first and last vertices will be connected.

>>> with turtle.poly():
...     turtle.forward(100)
...     turtle.right(60)
...     turtle.forward(100)

poly() is a context manager, so using it is the same as calling begin_poly() before the block and end_poly() after it:

>>> turtle.begin_poly()
>>> turtle.forward(100)
>>> turtle.right(60)
>>> turtle.forward(100)
>>> turtle.end_poly()

Added in version 3.14.

turtle.begin_poly()

Start recording the vertices of a polygon. The current turtle position is the first vertex of the polygon.

turtle.end_poly()

Stop recording the vertices of a polygon. The current turtle position is the last vertex of the polygon. This will be connected with the first vertex.

turtle.get_poly()

Devuelve el último polígono grabado.

>>> turtle.home()
>>> turtle.begin_poly()
>>> turtle.fd(100)
>>> turtle.left(20)
>>> turtle.fd(30)
>>> turtle.left(60)
>>> turtle.fd(50)
>>> turtle.end_poly()
>>> p = turtle.get_poly()
>>> register_shape("myFavouriteShape", p)
turtle.clone()

Create and return a clone of the turtle. The clone has the same position, heading and turtle properties.

>>> leonel = Turtle()
>>> marco = leonel.clone()
turtle.getturtle()
turtle.getpen()

Return the Turtle object itself.

Call getturtle() to get the turtle used by functions such as forward() and left():

>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x...>
turtle.getscreen()

Devuelve el objeto TurtleScreen sobre el cual la tortuga está dibujando. Los métodos TurtleScreen luego pueden ser llamados para ese objeto.

>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")
turtle.setundobuffer(size)
Parámetros:

size – un entero o None

Set or disable the undo buffer. If size is an integer, an empty undo buffer of the given size is installed. size is the maximum number of turtle actions that can be undone by undo(). If size is None, the undo buffer is disabled.

>>> turtle.setundobuffer(42)
turtle.undobufferentries()

Return the number of entries in the undo buffer.

>>> while turtle.undobufferentries():
...     turtle.undo()

Screen methods and functions

La mayoría de los ejemplos en esta sección se refieren a la instancia de TurtleScreen llamada screen.

Control de ventana

turtle.bgcolor()
turtle.bgcolor(color, /)
turtle.bgcolor(r, g, b, /)

Return or set the background color of the TurtleScreen.

Se permiten cuatro formatos de entrada:

bgcolor()

Return the current background color as a color specification string or as a tuple (see example). May be used as input to another color(), pencolor(), fillcolor() or bgcolor() call.

bgcolor(colorstring)

Set the background color to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c".

bgcolor((r, g, b))

Set the background color to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be between 0 and colormode, where colormode is either 1.0 or 255 (see colormode()).

bgcolor(r, g, b)

Set the background color to the RGB color represented by r, g, and b. Each of r, g, and b must be between 0 and colormode.

>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor("#800080")
>>> screen.bgcolor()
(128.0, 0.0, 128.0)
turtle.bgpic(picname=None)
Parámetros:

picname – a string or None

Set the background image or return the name of the current one. If picname is the name of an image file (PNG, GIF, PGM, and PPM), set that image as the background. If picname is "nopic", delete the background image, if present. If picname is None, return the filename of the current background image.

>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
'landscape.gif'
turtle.clear()

Nota

Este método de TurtleScreen está disponible como una función global solo bajo el nombre clearscreen. La función global clear es otra, derivada del método de Turtle clear.

turtle.clearscreen()

Borra todos los dibujos y todas las tortugas del la pantalla de la tortuga. Reinicia la ahora vacía pantalla de la tortuga a su estado inicial: fondo blanco, sin imagen de fondo, sin enlaces a eventos o seguimientos.

turtle.reset()

Nota

Este método TurtleScreen esta disponible como una función global solo bajo el nombre resetscreen. La función global reset es otra, derivada del método Turtle reset.

turtle.resetscreen()

Reset all turtles on the screen to their initial state.

turtle.screensize(canvwidth=None, canvheight=None, bg=None)
Parámetros:
  • canvwidth – a positive integer or None

  • canvheight – a positive integer or None

  • bg – a colorstring or None

Resize the canvas the turtles are drawing on. canvwidth and canvheight are the new width and height of the canvas in pixels, and bg is the new background color. If no arguments are given, return the current canvas width and height.

The drawing window is not altered. To see hidden parts of the canvas, use the scrollbars. This can make visible those parts of a drawing which were outside the canvas before, for example to find a turtle that has wandered off the canvas.

>>> screen.screensize()
(400, 300)
>>> screen.screensize(2000,1500)
>>> screen.screensize()
(2000, 1500)
turtle.setworldcoordinates(llx, lly, urx, ury)
Parámetros:
  • llx – un número

  • lly – un número

  • urx – un número

  • ury – un número

Set up a user-defined coordinate system. llx and lly are the x and y coordinates of the lower left corner of the canvas. urx and ury are the x and y coordinates of the upper right corner. Switch to mode «world» if necessary, which performs a reset. If mode «world» is already active, all drawings are redrawn according to the new coordinates. In user-defined coordinate systems, angles may appear distorted, see mode().

>>> screen.reset()
>>> screen.setworldcoordinates(-50,-7.5,50,7.5)
>>> for _ in range(72):
...     left(10)
...
>>> for _ in range(8):
...     left(45); fd(2)   # a regular octagon

Control de animación

turtle.no_animation()

Temporarily turn off turtle animation. The code inside the with block is not animated. Once the block is exited, the drawing appears. This is useful for drawing complex shapes where even the fastest speed setting is too slow.

>>> with screen.no_animation():
...     for dist in range(2, 400, 2):
...         fd(dist)
...         rt(90)

Added in version 3.14.

turtle.delay(delay=None)
Parámetros:

delay – a nonnegative integer or None

Return or set the drawing delay in milliseconds. This is approximately the time interval between two consecutive canvas updates. The longer the drawing delay, the slower the animation.

>>> screen.delay()
10
>>> screen.delay(5)
>>> screen.delay()
5
turtle.tracer(n=None, delay=None)
Parámetros:
  • n – a nonnegative integer or None

  • delay – a nonnegative integer or None

Turn turtle animation on or off and set the drawing delay. If n is given, only every n-th regular screen update is performed, which can be used to speed up the drawing of complex graphics. If n is 0, animation is turned off and the screen is only updated by calling update(). If delay is given, it sets the drawing delay, see delay(). When called without arguments, return the current value of n.

>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
...     fd(dist)
...     rt(90)
...     dist += 2
turtle.update()

Perform a TurtleScreen update. To be used when tracer() is turned off.

Ver también el método RawTurtle/Turtle speed().

Usando eventos de pantalla

turtle.listen(xdummy=None, ydummy=None)
Parámetros:
  • xdummy – ignored

  • ydummy – ignored

Set focus on the TurtleScreen so that it receives key events. The two dummy arguments are only there so that listen() can be passed to onclick().

turtle.onkey(fun, key)
turtle.onkeyrelease(fun, key)
Parámetros:
  • fun – una función sin argumentos o None

  • key – a string

Bind fun to the key-release event of key. key is a key, such as «a», or a key symbol, such as «space». If fun is None, the event binding is removed. To be able to receive key events, the TurtleScreen must have focus, see listen().

>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()

The turtle can then be moved by repeatedly pressing the up-arrow key, drawing a hexagon.

turtle.onkeypress(fun, key=None)
Parámetros:
  • fun – una función sin argumentos o None

  • key – a string or None

Bind fun to the key-press event of key. key is a key, such as «a», or a key symbol, such as «space». If key is not given, fun is bound to the key-press event of any key. If fun is None, the event binding is removed. To be able to receive key events, the TurtleScreen must have focus, see listen().

>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkeypress(f, "Up")
>>> screen.listen()

The turtle can then be moved by pressing or holding down the up-arrow key, drawing a hexagon.

turtle.onclick(fun, btn=1, add=None)
turtle.onscreenclick(fun, btn=1, add=None)
Parámetros:
  • fun – a function with two arguments or None

  • btn – an integer

  • add – a boolean or None

Bind fun to mouse-click events on this screen. fun is called with the coordinates of the clicked point on the canvas. If fun is None, existing bindings are removed. btn is the number of the mouse button and defaults to 1, the left mouse button. If add is True, a new binding is added, otherwise it replaces a previous binding.

Ejemplo de una instancia TurtleScreen llamada screen y una instancia Turtle llamada turtle:

>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>>                             # make the turtle move to the clicked point.
>>> screen.onclick(None)        # remove event binding again

Nota

Este método TurtleScreen está disponible como una función global solo bajo el nombre onscreenclick. La función global onclick es otra derivada del método Turtle onclick.

turtle.ontimer(fun, t=0)
Parámetros:
  • fun – una función sin argumentos

  • t – a nonnegative number

Instala un temporizador que llama a fun cada t milisegundos.

>>> running = True
>>> def f():
...     if running:
...         fd(50)
...         lt(60)
...         screen.ontimer(f, 250)
>>> f()  # makes the turtle march around
>>> running = False
turtle.mainloop()
turtle.done()

Start the event loop by calling Tkinter’s mainloop() method. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (see Ejecutando sin un subproceso).

Métodos de entrada

turtle.textinput(title, prompt)
Parámetros:
  • title – a string

  • prompt – a string

Pop up a dialog window for input of a string. title is the title of the dialog window and prompt is a text describing what information to input. Return the string entered. If the dialog is canceled, return None.

>>> screen.textinput("NIM", "Name of first player:")
turtle.numinput(title, prompt, default=None, minval=None, maxval=None)
Parámetros:
  • title – a string

  • prompt – a string

  • default – un número o None

  • minval – un número o None

  • maxval – un número o None

Pop up a dialog window for input of a number. title is the title of the dialog window and prompt is a text describing what numerical information to input. default is the default value, minval and maxval are the minimum and maximum values for input. If these are given and the number entered is not between minval and maxval, a hint is issued and the dialog remains open for correction. Return the number entered. If the dialog is canceled, return None.

>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)

Configuración y métodos especiales

turtle.mode(mode=None)
Parámetros:

mode – a string or None

Set the turtle mode and perform a reset. mode is one of the strings «standard», «logo» or «world». If mode is not given, return the current mode.

Mode «standard» is compatible with the old turtle module. Mode «logo» is compatible with most Logo turtle graphics. Mode «world» uses user-defined world coordinates, see setworldcoordinates(). In this mode, angles appear distorted if the x and y units are not of equal length.

Modo

Rumbo inicial de la tortuga

ángulos positivos

«standard»

hacia la derecha (este)

sentido antihorario

«logo»

hacia arriba (norte)

sentido horario

>>> mode("logo")  # resets turtle heading to north
>>> mode()
'logo'
turtle.colormode(cmode=None)
Parámetros:

cmode – un número o None

Return the colormode or set it to 1.0 or 255. After setting it, the r, g and b values of color triples have to be between 0 and cmode.

>>> screen.colormode(1)
>>> turtle.pencolor(240, 160, 80)
Traceback (most recent call last):
     ...
turtle.TurtleGraphicsError: bad color sequence: (240, 160, 80)
>>> screen.colormode()
1.0
>>> screen.colormode(255)
>>> screen.colormode()
255
>>> turtle.pencolor(240,160,80)
turtle.getcanvas()

Devuelve el lienzo de este TurtleScreen. Útil para conocedores que saben que hace con un TKinter Canvas.

>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas object ...>
turtle.getshapes()

Devuelve la lista de nombres de todas las formas de la tortuga actualmente disponibles.

>>> screen.getshapes()
['arrow', 'blank', 'circle', ..., 'turtle']
turtle.register_shape(name, shape=None)
turtle.addshape(name, shape=None)
Parámetros:
  • name – a string

  • shape – a string, a tuple of pairs of numbers, a Shape object or None

Add a turtle shape to the TurtleScreen’s shape list. It can be called in four different ways:

  1. name is the name of an image file (PNG, GIF, PGM, and PPM) and shape is None: Install the corresponding image shape.

    >>> screen.register_shape("turtle.gif")
    
  2. name is an arbitrary string and shape is the name of an image file (PNG, GIF, PGM, and PPM): Install the corresponding image shape.

    >>> screen.register_shape("turtle", "turtle.gif")
    
  3. name es una cadena de caracteres arbitraria y shape es una tupla de pares de coordenadas: Instala la forma poligonal correspondiente.

    >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
    
  4. name es una cadena arbitraria y shape es un objeto Shape (compuesto): instala la forma compuesta correspondiente.

Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle. To use a registered shape, call shape() with its name.

Distinto en la versión 3.14: Added support for PNG, PGM, and PPM image formats. Both a shape name and an image file name can be specified.

turtle.turtles()

Devuelve la lista de tortugas en la pantalla.

>>> for turtle in screen.turtles():
...     turtle.color("red")
turtle.window_height()

Devuelve la altura de la ventana de la tortuga.

>>> screen.window_height()
480
turtle.window_width()

Devuelve el ancho de la ventana de la tortuga.

>>> screen.window_width()
640
turtle.save(filename, *, overwrite=False)
Parámetros:
  • filename – a string

  • overwrite – un booleano

Save the current drawing and the turtles as a PostScript file. filename is the path of the file to create. It must end with ".ps" or ".eps". If a file with that name already exists, a FileExistsError is raised, unless overwrite is True. overwrite must be given by name, as in overwrite=True.

>>> screen.save("my_drawing.ps")
>>> screen.save("my_drawing.ps", overwrite=True)

Added in version 3.14.

Screen-only methods

turtle.bye()

Close the turtle graphics window.

turtle.exitonclick()

Bind bye() to mouse clicks on the screen and start the event loop. Clicking on the screen then closes the turtle graphics window. If the configuration value using_IDLE is True, the event loop is not started, see mainloop().

turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'])
Parámetros:
  • width – an integer or a float

  • height – an integer or a float

  • startx – un entero o None

  • starty – un entero o None

Set the size and position of the main window.

width and height are the size of the window. As integers they are sizes in pixels, as floats they are fractions of the screen, so 0.5 is half the screen. The defaults are 50% of the screen width and 75% of its height.

startx and starty are the position of the window. If positive, they are the distance in pixels from the left and top edges of the screen, if negative from the right and bottom edges. If None, the window is centered in that direction.

The default values of all arguments are stored in the configuration dictionary and can be changed with a turtle.cfg file.

>>> screen.setup(width=200, height=200, startx=0, starty=0)
>>> # sets window to 200x200 pixels, in upper left of screen
>>> screen.setup(width=0.75, height=0.5)
>>> # sets window to 75% of screen by 50% of screen and centers
turtle.title(titlestring)
Parámetros:

titlestring – a string

Set the title of the turtle window to titlestring. The title is shown in the title bar of the turtle graphics window.

>>> screen.title("Welcome to the turtle zoo!")

Clases públicas

class turtle.RawTurtle(canvas)
class turtle.RawPen(canvas)
Parámetros:

canvas – un tkinter.Canvas, un ScrolledCanvas o un TurtleScreen

Create a turtle. The turtle has all the methods described in Turtle methods and functions.

class turtle.Turtle

Subclase de RawTurtle, tiene la misma interface pero dibuja sobre una objeto por defecto Screen creado automáticamente cuando es necesario por primera vez.

class turtle.TurtleScreen(cv)
Parámetros:

cv – un tkinter.Canvas

Provides the screen-oriented methods, such as bgcolor(), that are described above.

class turtle.Screen

Subclass of TurtleScreen, with four methods added. Calling Screen() returns the single screen object. If it does not exist yet, it is created. Otherwise the existing one is returned.

class turtle.ScrolledCanvas(master)
Parámetros:

master – a Tkinter widget

A Tkinter canvas with scrollbars added. master is the widget that contains it. Used by class Screen, which thus automatically provides a ScrolledCanvas as playground for the turtles.

class turtle.Shape(type_, data=None)
Parámetros:
  • type_ – a string

  • data – depends on type_

Data structure modeling shapes. type_ is one of the strings «polygon», «image» or «compound». What data must be depends on type_: for «polygon» a tuple of pairs of coordinates, for «image» an image (only used internally), and for «compound» None, as a compound shape is built up using the addcomponent() method.

addcomponent(poly, fill, outline=None)
Parámetros:
  • poly – a tuple of pairs of numbers

  • fill – a color

  • outline – a color or None

Add a component to a shape of type «compound». poly is a polygon, a tuple of pairs of numbers. fill is the color the polygon is filled with and outline is the color of its outline. If outline is not given, fill is used for it as well.

Ejemplo:

>>> poly = ((0,0), (10,-5), (0,10), (-10,-5))
>>> s = Shape("compound")
>>> s.addcomponent(poly, "red", "blue")
>>> # ... add more components and then use register_shape()

Ver How to use compound shapes.

class turtle.Vec2D(x, y)

Una clase de vectores bidimensionales, usado como clase de ayuda para implementar gráficos de tortuga. Puede ser útil para los programas de gráficos de tortugas también. Derivado de la tupla, ¡por lo que un vector es una tupla!

Proporciona (para a, b vectores, k números)

  • a + b suma de vectores

  • a - b resta de vectores

  • a * b producto interno

  • k * a y a * k multiplicación con escalar

  • abs(a) valor absoluto de a

  • a.rotate(angle) rotación

Exceptions

The turtle module defines the following exception:

exception turtle.TurtleGraphicsError

Raised for invalid arguments or operations. For example, a malformed color string:

>>> turtle.color("blau")
Traceback (most recent call last):
    ...
turtle.TurtleGraphicsError: bad color string: blau

How-to guides

Esta sección cubre algunos casos de uso y enfoques típicos de las tortugas.

How to automatically begin and end filling

Starting with Python 3.14, you can use the fill() context manager instead of begin_fill() and end_fill() to automatically begin and end fill. Here is an example:

with fill():
    for i in range(4):
        forward(100)
        right(90)

forward(200)

The code above is equivalent to:

begin_fill()
for i in range(4):
    forward(100)
    right(90)
end_fill()

forward(200)

How to use compound shapes

Para usar formas complejas con la tortuga, que consiste en varios polígonos de diferentes colores, deberá usar la clase de ayuda Shape explícitamente como se describe debajo:

  1. Create an empty Shape object of type «compound».

  2. Agregue tantos componentes a este objeto como desee, utilizando el método addcomponent().

    Por ejemplo:

    >>> s = Shape("compound")
    >>> poly1 = ((0,0), (10,-5), (0,10), (-10,-5))
    >>> s.addcomponent(poly1, "red", "blue")
    >>> poly2 = ((0,0), (10,-5), (-10,-5))
    >>> s.addcomponent(poly2, "blue", "red")
    
  3. Now add the Shape to the Screen’s shape list and use it:

    >>> register_shape("myshape", s)
    >>> shape("myshape")
    

How to use the turtle module namespace

Usar from turtle import * es conveniente, pero tenga cuidado, ya que importa una colección bastante grande de objetos y, si está haciendo otra cosa que no sean gráficos de tortuga, corre el riesgo de un conflicto de nombres (esto se vuelve aún más problemático si está usando gráficos de tortuga en un script donde se pueden importar otros módulos).

La solución es utilizar import turtle: fd() se convierte en turtle.fd(), width() se convierte en turtle.width() y así sucesivamente. (Si escribir «tortuga» una y otra vez se vuelve tedioso, utilice, por ejemplo, import turtle as t en su lugar).

How to use turtle graphics in a script

Se recomienda utilizar el espacio de nombres del módulo turtle como se describe inmediatamente arriba, por ejemplo:

import turtle as t
from random import random

for i in range(100):
    steps = int(random() * 100)
    angle = int(random() * 360)
    t.right(angle)
    t.fd(steps)

Sin embargo, también se requiere otro paso: tan pronto como finalice el script, Python también cerrará la ventana de la tortuga. Agregar:

t.mainloop()

hasta el final del script. El script ahora esperará a que lo cierren y no saldrá hasta que lo hagan, por ejemplo, cerrando la ventana de gráficos de la tortuga.

How to use object-oriented turtle graphics

Aparte de para propósitos introductorios muy básicos o para probar cosas lo más rápido posible, es más habitual y mucho más potente utilizar el enfoque orientado a objetos para los gráficos de tortugas. Por ejemplo, esto permite tener varias tortugas en la pantalla a la vez.

En este enfoque, los distintos comandos de la tortuga son métodos de objetos (en su mayoría objetos Turtle). can utiliza el enfoque orientado a objetos en el shell, pero sería más típico en un script de Python.

El ejemplo anterior se convierte entonces en:

from turtle import Turtle
from random import random

t = Turtle()
for i in range(100):
    steps = int(random() * 100)
    angle = int(random() * 360)
    t.right(angle)
    t.fd(steps)

t.screen.mainloop()

Tenga en cuenta la última línea. t.screen es una instancia de Screen en la que existe una instancia de Turtle; se crea automáticamente junto con la tortuga.

La pantalla de la tortuga se puede personalizar, por ejemplo:

t.screen.title('Object-oriented turtle demo')
t.screen.bgcolor("orange")

How to use help()

Los métodos públicos de las clases Screen y Turtle están ampliamente documentados a través de cadenas de documentación. Por lo tanto, estos se pueden usar como ayuda en línea a través de las instalaciones de ayuda de Python:

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

  • Llamar a help() en métodos o funciones muestra los docstrings:

    >>> help(TurtleScreen.bgcolor)
    Help on function bgcolor in module turtle:
    
    bgcolor(self, *args)
        Return or set the background color of the TurtleScreen.
    
        Four input formats are allowed:
          - bgcolor()
            Return the current background color as a color specification
            string or as a tuple (see example).  May be used as input
            to another color(), pencolor(), fillcolor() or bgcolor() call.
          - bgcolor(colorstring)
            Set the background color to colorstring, which is a Tk color
            specification string, such as "red", "yellow", or "#33cc8c".
          - bgcolor((r, g, b))
            Set the background color to the RGB color represented by
            the tuple of r, g, and b.  Each of r, g, and b must be
            between 0 and colormode, where colormode is either 1.0 or 255
            (see colormode()).
          - bgcolor(r, g, b)
            Set the background color to the RGB color represented by
            r, g, and b.  Each of r, g, and b must be between 0 and
            colormode.
    
        Example (for a TurtleScreen instance named screen):
            >>> screen.bgcolor("orange")
            >>> screen.bgcolor()
            'orange'
            >>> screen.colormode(255)
            >>> screen.bgcolor("#800080")
            >>> screen.bgcolor()
            (128.0, 0.0, 128.0)
    
    >>> help(Turtle.penup)
    Help on function penup in module turtle:
    
    penup(self)
        Lift the pen.
    
        Aliases: penup | pu | up
    
        The turtle does not draw when it moves.
    
  • Los docstrings de las funciones que se derivan de los métodos tienen una forma modificada:

    >>> help(bgcolor)
    Help on function bgcolor in module turtle:
    
    bgcolor(*args)
        Return or set the background color of the TurtleScreen.
    
        Four input formats are allowed:
          - bgcolor()
            Return the current background color as a color specification
            string or as a tuple (see example).  May be used as input
            to another color(), pencolor(), fillcolor() or bgcolor() call.
          - bgcolor(colorstring)
            Set the background color to colorstring, which is a Tk color
            specification string, such as "red", "yellow", or "#33cc8c".
          - bgcolor((r, g, b))
            Set the background color to the RGB color represented by
            the tuple of r, g, and b.  Each of r, g, and b must be
            between 0 and colormode, where colormode is either 1.0 or 255
            (see colormode()).
          - bgcolor(r, g, b)
            Set the background color to the RGB color represented by
            r, g, and b.  Each of r, g, and b must be between 0 and
            colormode.
    
        Example:
            >>> bgcolor("orange")
            >>> bgcolor()
            'orange'
            >>> colormode(255)
            >>> bgcolor("#800080")
            >>> bgcolor()
            (128.0, 0.0, 128.0)
    
    >>> help(penup)
    Help on function penup in module turtle:
    
    penup()
        Lift the pen.
    
        Aliases: penup | pu | up
    
        The turtle does not draw when it moves.
    

Estos docstrings modificados se crean automáticamente junto con las definiciones de función que se derivan de los métodos en el momento de la importación.

Traducción de cadenas de documentos a diferentes idiomas

The docstrings of the public methods of the Screen and Turtle classes, and of the corresponding functions, can be replaced with translations, so that help() and IDE tooltips are shown in another language. However, only the help text is translated, the names of the functions and methods stay the same.

Translations are distributed on PyPI in the turtle-translations package. To use them, install the package with pip and select the language with the PYTHON_TURTLE_LANG environment variable. For example, to show the help text in Spanish:

$ python -m pip install turtle-translations
$ PYTHON_TURTLE_LANG=es python
>>> import turtle
>>> help(turtle.forward)

The language can also be set permanently with the language entry of the turtle.cfg file (see Cómo configurar Screen and Turtles). If no translation is found for the selected language, the English docstrings are kept.

To add a new language or improve an existing translation, see the contribution instructions in the turtle-translations project.

A translation is a docstring dictionary. It is a top-level module named turtle_docstringdict_language.py on sys.path defining a dictionary named docsdict, the keys of which are method names such as Turtle.forward and the values of which are the translated docstrings. It is read in at import time. Entries naming a method which does not exist in the running version are ignored.

Distinto en la versión 3.16: Entries naming an unknown method are ignored instead of reported.

PYTHON_TURTLE_LANG

The name of the language to read the translation for. It takes precedence over the language entry of the turtle.cfg file.

Added in version 3.16.

turtle.write_docstringdict(filename='turtle_docstringdict')
Parámetros:

filename – a string

Write the docstring dictionary to a Python script. The dictionary is written to the file filename.py. It is intended to serve as a template for translating the docstrings into different languages. This function has to be called explicitly. It is not used by the turtle graphics classes.

Cómo configurar Screen and Turtles

La configuración predeterminada incorporada imita la apariencia y el comportamiento del antiguo módulo de tortuga para mantener la mejor compatibilidad posible con él.

If you want to use a different configuration which better reflects the features of this module or which better fits to your needs, for example 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

Breve explicación de las entradas seleccionadas:

  • Las primeras cuatro líneas corresponden a los argumentos del método Screen.setup.

  • Las líneas 5 y 6 corresponden a los argumentos del método Screen.screensize.

  • shape can be any of the built-in shapes, such as arrow or turtle. For more information, see shape().

  • If you want to use no fill color (that is, make the turtle transparent), you have to write fillcolor = "" (but all nonempty strings must not have quotes in the cfg file).

  • If you want the turtle’s appearance to reflect its state, you have to set resizemode = auto.

  • The language entry selects the language of the docstrings, unless the PYTHON_TURTLE_LANG environment variable is set. See Traducción de cadenas de documentos a diferentes idiomas for more information.

  • Las entradas exampleturtle y examplescreen definen los nombres de estos objetos a medida que aparecen en las cadenas de documentos. La transformación de método-docstrings en función-docstrings eliminará estos nombres de las docstrings.

  • using_IDLE: Set this to True if you regularly work with IDLE and its -n switch («no subprocess»). This will prevent exitonclick() from entering the mainloop.

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

El directorio Lib/turtledemo contiene un archivo turtle.cfg. Puede estudiarlo como un ejemplo y ver sus efectos al ejecutar las demostraciones (preferiblemente no desde el visor de demostraciones).

Explicación

A turtle object draws on a screen object, and there are a number of key classes in the turtle object-oriented interface that can be used to create them and relate them to each other.

Una instancia Turtle creará automáticamente una instancia Screen si aún no hay una presente.

Turtle es una subclase de RawTurtle, que crea automáticamente una superficie de dibujo. Para ello, será necesario proporcionar o crear una canvas. La canvas puede ser una tkinter.Canvas, una ScrolledCanvas o una TurtleScreen.

TurtleScreen es la superficie de dibujo básica de una tortuga. Screen es una subclase de TurtleScreen e incluye some additional methods para gestionar su apariencia (incluido el tamaño y el título) y su comportamiento. El constructor de TurtleScreen necesita un tkinter.Canvas o un ScrolledCanvas como argumento.

La interfaz funcional para gráficos de tortugas utiliza los distintos métodos de Turtle y TurtleScreen/Screen. En segundo plano, se crea automáticamente un objeto de pantalla cada vez que se llama a una función derivada de un método Screen. De manera similar, se crea automáticamente un objeto de tortuga cada vez que se llama a cualquiera de las funciones derivadas de un método de Turtle.

Para utilizar varias tortugas en una pantalla, se debe utilizar la interfaz orientada a objetos.

turtledemo — Demo scripts

The turtledemo package includes a set of demo scripts. These scripts can be run and viewed using the supplied demo viewer as follows:

python -m turtledemo

Alternativamente, puede ejecutar los scripts de demostración individualmente. Por ejemplo,

python -m turtledemo.bytedesign

The turtledemo package directory contains:

  • Un visor de demostración __main__.py que se puede utilizar para ver el código fuente de los scripts y ejecutarlos al mismo tiempo.

  • Multiple scripts demonstrating different features of the turtle module. Examples can be accessed via the Examples menu. They can also be run standalone.

  • Un archivo turtle.cfg que sirve como ejemplo de cómo escribir y usar dichos archivos.

Los scripts de demostración son:

Nombre

Descripción

Características

bytedesign

patrón de gráficos de tortuga clásica compleja

tracer(), delay(), update()

chaos

gráficos dinámicos de Verhulst, muestra que los cálculos de la computadora pueden generar resultados a veces contra las expectativas del sentido común

coordenadas mundiales

clock

reloj analógico que muestra la hora de su computadora

turtles as clock’s hands, ontimer()

colormixer

experimento con r, g, b

ondrag()

forest

3 árboles de ancho primero

aleatorización

fractalcurves

Curvas Hilbert & Koch

recursión

lindenmayer

ethnomathematics (Indian kolams)

Sistema-L

minimal_hanoi

Torres de Hanoi

Rectangular Turtles as Hanoi discs (shape(), shapesize())

nim

juega el clásico juego de nim con tres montones de palos contra la computadora.

tortugas como nimsticks, impulsado por eventos (mouse, teclado)

paint

programa de dibujo super minimalista

onclick()

peace

elemental

turtle: apariencia y animación

penrose

embaldosado aperiódico con cometas y dardos

stamp()

planet_and_moon

simulación de sistema gravitacional

formas compuestas, Vec2D

rosette

a pattern from the Wikipedia article on turtle graphics

clone(), undo()

round_dance

tortugas bailarinas que giran por parejas en dirección opuesta

compound shapes, clone(), shapesize(), tilt(), get_shapepoly(), update()

sorting_animate

demostración visual de diferentes métodos de ordenamiento

alineación simple, aleatorización

tree

un primer árbol de amplitud (gráfico, usando generadores)

clone()

two_canvases

diseño simple

tortugas en dos lienzos (two_canvases)

yinyang

otro ejemplo elemental

circle()

¡Diviértete!