Python: How do I use the turtle library?

Edited

The turtle is a Python module that allows you to draw on your screen using code.

You can check the official Python documentation for the turtle library here: https://docs.python.org/3/library/turtle.html

Setting up the Canvas

The first thing you need to do to use the turtle module is add the following line to import it into your program.

import turtle

Now that you have the turtle library imported to your project, you need to setup a canvas so that you can start drawing.

screen = turtle.Screen() # get the Turtle Screen

You can set the color of the background using the following line. Replace "blue" with another color if you want to have a different color for your background.

screen.bgcolor("blue")

Creating a Turtle

Next, we need to create a turtle object so we can start drawing shapes.

t = turtle.Turtle() #create a new turtle

Moving the Turtle

When a turtle is created, it will be facing to the right. You can move your turtle in the direction it is currently facing using the forward method.

t.forward(100)

To turn the turtle in a new direction, use the right() and left() functions. The following command will turn the turtle 90 degrees to the left.

t.left(90)

Alternatively, you can use coordinates to tell your turtle where to go. To tell the turtle to go to a position on the canvas, use the goto method.

t.goto(0, 100)

Drawing with the Turtle

Your turtle doesn't always have to leave a trail as it moves. You can control when to draw or not by using the penup() and pendown() functions.

When the pen is lifted, the turtle will stop tracing its path on the canvas until the pendown() function is called.

t.penup()
t.pendown()

You can draw a shape at the current position of your turtle by calling the shape function on the turtle.

t.shape("square")

By default, the turtle comes with the following shapes to choose from: 'arrow', 'turtle', 'circle', 'square', 'triangle', and 'classic'. Try a few of these out to see what they look like!

Sample Project

Use the turtle tool to try to draw some creations of your own. Maybe something in the following drawing will inspire you!

python-turtle-landscape.gif