The Turtle module allows you to interactively move animated turtles around.
By default, they draw their path as they move, so you can use them to draw shapes.
# Create a new turtle.
turtle = Turtle()
# Move the turtle forward 30 pixels.
turtle.forward(30)
# Turn the turtle right 45 degrees.
turtle.right(45)
# Move the turtle forward 100 pixels.
turtle.forward(100)
Parameters: |
|
---|
turtle = Turtle()
Move the turtle forward.
Parameters: | distance (float) – the number of pixels you want the turtle moved forward. |
---|
turtle.forward(100)
Turn the turtle right.
Parameters: | degrees (float) – the degrees you want the turtle turned right. |
---|
turtle.right(45)
Turn the turtle left.
Parameters: | degrees (float) – the degrees you want the turtle turned left. |
---|
turtle.left(90)
Set the angle at which the turtle faces.
Parameters: | to_angle (float) – the angle, in degrees, which the turtle will face. 0.0 degrees faces right. 180.0 degrees faces left. |
---|
# Point the turtle straight up.
turtle.setheading(90)
# Point the turtle straight down.
turtle.setheading(270)
Set the position of the turtle to (x, y).
Parameters: |
|
---|
# Move the turtle from its current position to 100 pixels above the center, and 100 pixels to the right.
turtle.setpos(100, 100)
Move the turtle from its current location to (x, y).
Parameters: |
|
---|
# Move the turtle from its current position to 50 pixels above the center, and 50 pixels to the right.
turtle.goto(50, 50)
Stop the turtle from drawing its movement path.
turtle.penup()
Let the turtle draw its path again.
turtle.pendown()
Fill in a shape as the turtle draws it.
turtle.begin_fill()
Stop filling in a shape as the turtle draws it.
turtle.end_fill()
Set the color of a turtle or its pen.
Parameters: | color (string) – the turtle and pen’s new color. |
---|
turtle.color('red')
Parameters: |
|
---|
turtle.color('red', 'cyan')
Make a turtle faster or slower.
Parameters: | speed (float) – the new speed of the turtle. |
---|
turtle.speed(5)
turtle.forward(20)
# The turtle should move twice as fast now.
turtle.speed(10)
turtle.forward(20)
# This makes the animation happen instantly.
turtle.speed(0)
Change a turtle’s shape.
Parameters: | shape (string) – the new shape of the turtle. |
---|
# Change the turtle to an arrow.
turtle.shape('arrow')
# Change the turtle back to a turtle.
turtle.shape('turtle')
# Change the turtle to a circle.
turtle.shape('circle')
# Change the turtle to a square.
turtle.shape('square')
# Change the turtle to a triangle.
turtle.shape('triangle')
# Change the shape to a cursor.
turtle.shape('classic')