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()orradians(). How the heading is measured depends on the turtle mode, seemode().>>> 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()orradians(). How the heading is measured depends on the turtle mode, seemode().>>> 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 aVec2D, for example as returned bypos(). 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
Noney – un número o
Nonefill_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=Trueto keep filling one shape instead. The teleport then counts as an edge of the shape, as it would withgoto().>>> 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
Nonesteps – 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 counterclockwise direction if radius is positive, otherwise in 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
Nonecolor – 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 + 4and2 * pensizeis 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()¶
Estampa una copia de la forma de la tortuga en el lienzo en la posición actual. Devuelve un stamp_id por cada estampa, que puede ser usado para borrarlo al llamar
clearstamp(stamp_id).>>> turtle.color("blue") >>> stamp_id = turtle.stamp() >>> turtle.fd(50)
- turtle.clearstamp(stampid)¶
- Parámetros:
stampid – un entero, debe devolver el valor de la llamada previa de la función
stamp()call
Borra la estampa con el stampid dado.
>>> 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)
Borra todas o las primeros/últimos n estampas de la tortuga. Si n es
None, borra todas las estampas, Si n > 0 borra la primera estampa n, sino y n < 0 borra la última estampa n.>>> for i in range(8): ... unused_stamp_id = turtle.stamp() ... turtle.fd(30) >>> turtle.clearstamps(2) >>> turtle.clearstamps(-2) >>> turtle.clearstamps()
- turtle.undo()¶
Deshace (repetidamente) la(s) última(s) acción(es) de la tortuga. El número de acciones a deshacer es determinado por el tamaño del undobuffer.
>>> 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. If speed is a number greater than 10 or smaller than 0.5, the speed is set 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()andback()make the turtle jump, and likewiseleft()andright()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
Vec2Dvector.>>> 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, aVec2D, for example as returned bypos(), or another turtle. The angle is measured from the turtle’s start orientation, which depends on the turtle mode, seemode().>>> 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, aVec2D, for example as returned bypos(), 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.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 – un diccionario con algunos o todos las claves listadas debajo
pendict – uno o más argumentos-palabras claves con las claves listadas debajo como palabras claves
Devuelve o establece los atributos del lápiz en un «diccionario-lápiz» con el siguiente para de valores/claves:
«shown»: True/False
«pendown»: True/False
«pencolor»: color-string or color-tuple
«fillcolor»: color-string or color-tuple
«pensize»: número positivo
«speed»: número en el rango 0..10
«resizemode»: «auto» or «user» or «noresize»
«stretchfactor»: (número positivo, número positivo)
«outline»: número positivo
«tilt»: número
Este diccionario puede usarse como argumento de una llamada subsecuente a la función
pen()para restaurar el estado anterior del lápiz. Más aún, uno o más de estos atributos pueden darse como argumentos claves. Esto puede usarse para establecer diferentes atributos del lápiz en una sola definición.>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10) >>> sorted(turtle.pen().items()) [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'), ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'), ('shearfactor', 0.0), ('shown', True), ('speed', 9), ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)] >>> penstate=turtle.pen() >>> turtle.color("yellow", "") >>> turtle.penup() >>> sorted(turtle.pen().items())[:3] [('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')] >>> turtle.pen(penstate, fillcolor="green") >>> sorted(turtle.pen().items())[:3] [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]
- turtle.isdown()¶
Return
Trueif the pen is down,Falseif 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()orbgcolor()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()orbgcolor()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()yfillcolor().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)yfillcolor(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
Trueif the turtle is filling,Falseotherwise.>>> turtle.begin_fill() >>> if turtle.filling(): ... turtle.pensize(5) ... else: ... turtle.pensize(3)
- turtle.fill()¶
Fill the shape drawn in the
with turtle.fill():block.>>> turtle.color("black", "red") >>> with turtle.fill(): ... turtle.circle(80)
Using
fill()is equivalent to adding thebegin_fill()before the fill-block andend_fill()after the fill-block:>>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(80) >>> turtle.end_fill()
Added in version 3.14.
- turtle.begin_fill()¶
Para ser llamada justo antes de dibujar una forma a rellenar.
- turtle.end_fill()¶
Rellena la forma dibujada después de última llamada a la función
begin_fill().Superponer o no, regiones de polígonos auto-intersectados o múltiples formas, estas son rellenadas dependiendo de los gráficos del sistema operativo, tipo de superposición y número de superposiciones. Por ejemplo, la flecha de la tortuga de arriba, puede ser toda amarilla o tener algunas regiones blancas.
>>> 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 – objeto que se escribirá en TurtleScreen
move – True/False
align – una de las frases «left», «center» o «right»
font – un trio (nombre de fuente, tamaño de fuente, tipo de fuente)
Escribe texto - la representación de cadena de caracteres de arg - en la posición actual de la tortuga de acuerdo con align («izquierda», «centro» o «derecha») y con la fuente dada. Si mov es verdadero, el lápiz se mueve a la esquina inferior derecha del texto. De forma predeterminada, move es
False.>>> 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.isvisible()¶
Return
Trueif the turtle is visible,Falseif 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 dictionary. Initially there are the following shapes: «arrow», «turtle», «circle», «square», «triangle» and «classic». To add shapes, see theScreenmethodregister_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ónshapesize()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
Nonestretch_len – a positive number or
Noneoutline – 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 – número (opcional)
Establece o devuelve el valor actual del estiramiento. Estira la forma de la tortuga de acuerdo a la inclinación del factor de corte, que es la tangente del ángulo de corte. No cambia el rumbo de la tortuga (dirección del movimiento). Si no de da un valor de inclinación: devuelve el factor actual, por ejemplo la tangente del ángulo de inclinación, por el cual se cortan la líneas paralelas al rumbo de la tortuga.
>>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.shearfactor(0.5) >>> turtle.shearfactor() 0.5
- turtle.tilt(angle)¶
- Parámetros:
angle – un número
Rota la forma de la tortuga en ángulo desde su ángulo de inclinación actual, pero no cambia el rumbo de la tortuga (dirección del movimiento).
>>> 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 (opcional)
Establece o devuelve el ángulo de inclinación actual. Si se otorga un ángulo, rota la forma de la tortuga para apuntar en la dirección del ángulo especificado, independientemente de su actual ángulo de inclinación. No cambia el rumbo de la tortuga (dirección del movimiento). Si no se da el ángulo: devuelve el ángulo de inclinación actual, por ejemplo: el ángulo entre la orientación de la forma de la tortuga y el rumbo de la tortuga (su dirección de movimiento).
>>> 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 (opcional)
t12 – un número (opcional)
t21 – un número (opcional)
t12 – un número (opcional)
Establece o devuelve la matriz de transformación actual de la forma de la tortuga.
Si no se proporciona ninguno de los elementos de la matriz, retorna la matriz de transformación como una tupla de 4 elementos. De lo contrario, establezca los elementos dados y transforme la forma de tortuga de acuerdo con la matriz que consta de la primera fila t11, t12 y la segunda fila t21, t22. El determinante t11 * t22 - t12 * t21 no debe ser cero, de lo contrario se genera un error. Modifique el factor de estiramiento, el factor de corte y el ángulo de inclinación de acuerdo con la matriz dada.
>>> 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()¶
Devuelve el polígono de la forma actual como tupla de pares de coordenadas. Esto puede ser usado para definir una nueva forma o componentes de una forma compuesta.
>>> 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
Nonebtn – 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 isTrue, a new binding is added, otherwise it replaces a former 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 – una función con dos argumentos que se invocará con las coordenadas del punto en el que se hizo clic en el lienzo
btn – número del botón del mouse, el valor predeterminado es 1 (botón izquierdo del mouse)
add –
TrueoFalse– si esTrue, se agrega un nuevo enlace, de lo contrario reemplazará el enlace anterior
Enlaza acciones divertidas a eventos del tipo soltar botón del mouse en la tortuga. SI la acción es
None, las acciones asociadas son borradas.>>> 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 – una función con dos argumentos que se invocará con las coordenadas del punto en el que se hizo clic en el lienzo
btn – número del botón del mouse, el valor predeterminado es 1 (botón izquierdo del mouse)
add –
TrueoFalse– si esTrue, se agrega un nuevo enlace, de lo contrario reemplazará el enlace anterior
Enlaza acciones divertidas a eventos en los movimientos del mouse. Si la acción es
None, las acciones asociadas son borradas.Observación: cada secuencia de los eventos de movimiento del mouse en una tortuga es precedida por un evento de click del mouse en esa tortuga.
>>> turtle.ondrag(turtle.goto)
Subsecuentemente, clickear y arrastrar la Tortuga la moverá a través de la pantalla produciendo dibujos a mano alzada (si el lápiz está abajo).
Métodos especiales de Turtle¶
- turtle.poly()¶
Record the vertices of a polygon drawn in the
with turtle.poly():block. The first and last vertices will be connected.>>> with turtle.poly(): ... turtle.forward(100) ... turtle.right(60) ... turtle.forward(100)
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 asforward()andleft():>>> pet = getturtle() >>> pet.fd(50) >>> pet <turtle.Turtle object at 0x...>
- turtle.getscreen()¶
Devuelve el objeto
TurtleScreensobre 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 isNone, the undo buffer is disabled.>>> turtle.setundobuffer(42)
- turtle.undobufferentries()¶
Return the number of entries in the undo buffer.
>>> while undobufferentries(): ... 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()orbgcolor()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, name of an image file (PNG, GIF, PGM, and PPM) or
"nopic", orNone
Establece la imagen de fondo o devuelve el nombre de la imagen de fondo actual. Si picname es un nombre de archivo, establece la imagen correspondiente como fondo. Si picname es
"nopic", borra la imagen de fondo, si hay alguna presente. Si picname esNone, devuelve el nombre de archivo de la imagen de fondo actual.>>> 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 globalcleares otra, derivada del método de Turtleclear.
- 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 globalresetes otra, derivada del método Turtlereset.
- turtle.resetscreen()¶
Reset all turtles on the screen to their initial state.
- turtle.screensize(canvwidth=None, canvheight=None, bg=None)¶
- Parámetros:
canvwidth – entero positivo, nueva anchura del lienzo en pixeles
canvheight – entero positivo, nueva altura del lienzo en pixeles
bg – colorstrng o tupla de color, muevo color de fondo
Si no se dan argumentos, devuelve el actual (ancho y alto del lienzo). Sino redimensiona el lienzo en el que la tortuga está dibujando. No altera la ventana de dibujo. Para ver las partes ocultas del lienzo, use la barra de desplazamiento. Con este método, se pueden hacer visibles aquellas partes de un dibujo que antes estaban fuera del lienzo.
>>> screen.screensize() (400, 300) >>> screen.screensize(2000,1500) >>> screen.screensize() (2000, 1500)
ej. buscar una tortuga que se escapó por error ;-)
- 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
withblock 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
Nonedelay – 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, seedelay(). 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()¶
Realiza una actualización de la pantalla de la tortuga. Para ser usada cuando tracer está deshabilitada.
Ver también el método RawTurtle/Turtle speed().
Usando eventos de pantalla¶
- turtle.listen(xdummy=None, ydummy=None)¶
Establece el foco en la pantalla de la tortuga (para recoger eventos de teclado). Los argumentos dummy se proveen en orden de ser capaces de pasar
listen()a los métodos onclick.
- turtle.onkey(fun, key)¶
- turtle.onkeyrelease(fun, key)¶
- Parámetros:
fun – una función sin argumentos o
Nonekey – una cadena de caracteres: tecla (por ejemplo, «a») o una acción del teclado (por ejemplo, «space»)
Vincula fun a un evento de liberación de una tecla. Si fun es
None, los eventos vinculados son removidos. Aclaración: para poder registrar eventos de teclado, TurtleScreen tiene que tener el foco. (ver el métodolisten().)>>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen()
- turtle.onkeypress(fun, key=None)¶
- Parámetros:
fun – una función sin argumentos o
Nonekey – una cadena de caracteres: tecla (por ejemplo, «a») o una acción del teclado (por ejemplo, «space»)
Vincula fun a un evento de pulsado de una tecla, o a cualquier evento de pulsado de tecla si no se da una. Aclaración: para poder registrar eventos de teclado, TurtleScreen tiene que tener el foco. (ver el método
listen().)>>> def f(): ... fd(50) ... >>> screen.onkey(f, "Up") >>> screen.listen()
- turtle.onclick(fun, btn=1, add=None)¶
- turtle.onscreenclick(fun, btn=1, add=None)¶
- Parámetros:
fun – a function with two arguments or
Nonebtn – 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 isTrue, a new binding is added, otherwise it replaces a former binding.Ejemplo de una instancia TurtleScreen llamada
screeny una instancia Turtle llamadaturtle:>>> 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 globalonclickes otra derivada del método Turtleonclick.
- turtle.ontimer(fun, t=0)¶
- Parámetros:
fun – una función sin argumentos
t – un número >= 0
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
Noneminval – un número o
Nonemaxval – 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, the number entered must be between minval and maxval. If not, 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
turtlemodule. Mode «logo» is compatible with most Logo turtle graphics. Mode «world» uses user-defined world coordinates, seesetworldcoordinates(). 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): ... 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
Shapeobject orNone
Add a turtle shape to the TurtleScreen’s shape list. It can be called in four different ways:
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")
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")
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)))
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
Screen-only methods¶
- turtle.bye()¶
Close the turtle graphics window.
- turtle.exitonclick()¶
Ata el método
bye()al click del ratón sobre la pantalla.Si el valor «using_IDLE» en la configuración del diccionario es
False(valor por defecto), también ingresa mainloop. Observaciones: si se usa la IDLE con el modificador (no subproceso)-n, este valor debe establecerse aTrueenturtle.cfg. En este caso el propio mainloop de la IDLE está activa también para script cliente.
- turtle.save(filename, overwrite=False)¶
Save the current turtle drawing (and turtles) as a PostScript file.
- Parámetros:
filename – the path of the saved PostScript file
overwrite – if
Falseand there already exists a file with the given filename, then the function will raise aFileExistsError. If it isTrue, the file will be overwritten.
>>> screen.save("my_drawing.ps") >>> screen.save("my_drawing.ps", overwrite=True)
Added in version 3.14.
- turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'])¶
Establece el tamaño y la posición de la ventana principal. Los valores por defecto de los argumentos son guardados en el diccionario de configuración y puede ser cambiado a través del archivo
turtle.cfg.- Parámetros:
width – si es un entero, el tamaño en pixeles, si es un número flotante, una fracción de la pantalla; el valor por defecto es 50% de la pantalla
height – si es un entero, la altura en pixeles, si es un número flotante, una fracción de la pantalla; el valor por defecto es 75% de la pantalla
startx – si es positivo, punto de inicio en pixeles desde la esquina izquierda de la pantalla, si es negativo desde la esquina derecha de la pantalla, si es
None, centra la ventana horizontalmentestarty – si es positivo, punto de inicio en pixeles desde la parte superior de la pantalla, si es negativo desde la parte inferior de la pantalla, si es
None, centra la ventana verticalmente
>>> screen.setup (width=200, height=200, startx=0, starty=0) >>> # sets window to 200x200 pixels, in upper left of screen >>> screen.setup(width=.75, height=0.5, startx=None, starty=None) >>> # 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, unScrolledCanvaso unTurtleScreen
Crea una tortuga. La tortuga tiene todos los métodos descriptos anteriormente como «métodos de «Turtle/RawTurtle».
- class turtle.Turtle¶
Subclase de RawTurtle, tiene la misma interface pero dibuja sobre una objeto por defecto
Screencreado automáticamente cuando es necesario por primera vez.
- class turtle.TurtleScreen(cv)¶
- Parámetros:
cv – un
tkinter.Canvas
Proporciona métodos orientados a la pantalla como
bgcolor(), etc., que se describen anteriormente.
- class turtle.Screen¶
Subclass of
TurtleScreen, with four methods added. CallingScreen()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 – algunos widgets TKinter para contener el ScrollCanvas, por ejemplo un lienzo Tkinter con barras de desplazamiento agregadas
Usado por la clase Screen, que proporciona automáticamente un ScrolledCanvas como espacio de trabajo para las tortugas.
- class turtle.Shape(type_, data)¶
- 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 theaddcomponent()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()
- 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 + bsuma de vectoresa - bresta de vectoresa * bproducto internok * aya * kmultiplicación con escalarabs(a)valor absoluto de aa.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:
Create an empty
Shapeobject of type «compound».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")
Ahora agregar la forma a la lista de formas de la pantalla y úsela:
>>> 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¶
Ver también
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:
Cuando se usa IDLE, la información sobre herramientas muestra las firmas y las primeras líneas de las cadenas de documentos de las llamadas de función/método escritas.
Llamar a
help()en métodos o funciones muestra los 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()
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) 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()
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.cfgfile.Added in version 3.16.
- turtle.write_docstringdict(filename='turtle_docstringdict')¶
- Parámetros:
filename – una cadena de caracteres, utilizada como nombre de archivo
Crea y escribe un diccionario-docstring en un script de Python con el nombre de archivo dado. Esta función tiene que ser llamada explícitamente (no es utilizada por las clases de gráficos de tortugas). El diccionario de docstrings se escribirá en el script de Python
filename.py. Está destinado a servir como plantilla para la traducción de las cadenas de documentos a diferentes idiomas.
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.
Si desea utilizar una configuración diferente que refleje mejor las características de este módulo o que se adapte mejor a sus necesidades, por ejemplo, para su uso en un aula, puede preparar un archivo de configuración turtle.cfg que se leerá en el momento de la importación y modificará la configuración de acuerdo con su configuración.
La configuración incorporada correspondería al siguiente 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 puede ser cualquiera de las formas integradas, por ejemplo: arrow, turtle, etc. Para obtener más información, pruebe con
help(shape).Si no desea utilizar ningún color de relleno (es decir, hacer que la tortuga sea transparente), debe escribir
fillcolor = ""(pero todas las cadenas no vacías no deben tener comillas en el archivo cfg).Si desea reflejar el estado de la tortuga, debe usar
resizemode = auto.The language entry selects the language of the docstrings, unless the
PYTHON_TURTLE_LANGenvironment 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: Establezca esta opción en
Truesi trabaja habitualmente con IDLE y su opción-n(«sin subproceso»). Esto evitará queexitonclick()ingrese al bucle principal.
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¶
Un objeto tortuga se dibuja en un objeto de pantalla, y hay una serie de clases clave en la interfaz orientada a objetos tortuga que se pueden usar para crearlos y relacionarlos entre sí.
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__.pyque se puede utilizar para ver el código fuente de los scripts y ejecutarlos al mismo tiempo.Multiple scripts demonstrating different features of the
turtlemodule. Examples can be accessed via the Examples menu. They can also be run standalone.Un archivo
turtle.cfgque sirve como ejemplo de cómo escribir y usar dichos archivos.
Los scripts de demostración son:
Nombre |
Descripción |
Características |
|---|---|---|
|
patrón de gráficos de tortuga clásica compleja |
|
|
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 |
|
reloj analógico que muestra la hora de su computadora |
turtles as clock’s
hands, |
|
experimento con r, g, b |
|
|
3 árboles de ancho primero |
aleatorización |
|
Curvas Hilbert & Koch |
recursión |
|
etnomatemáticas (kolams indios) |
Sistema-L |
|
Torres de Hanoi |
Rectangular Turtles
as Hanoi discs
( |
|
juega el clásico juego de nim con tres montones de palos contra la computadora. |
tortugas como nimsticks, impulsado por eventos (mouse, teclado) |
|
programa de dibujo super minimalista |
|
|
elemental |
turtle: apariencia y animación |
|
embaldosado aperiódico con cometas y dardos |
|
|
simulación de sistema gravitacional |
formas compuestas, |
|
un patrón del artículo de wikipedia sobre gráficos de tortuga (turtle) |
|
|
tortugas bailarinas que giran por parejas en dirección opuesta |
compound shapes, |
|
demostración visual de diferentes métodos de ordenamiento |
alineación simple, aleatorización |
|
un primer árbol de amplitud (gráfico, usando generadores) |
|
|
diseño simple |
tortugas en dos lienzos (two_canvases) |
|
otro ejemplo elemental |
¡Diviértete!