Python Turtle Graphics: Create Visual Art with Code

When I was working on a project, I needed to create some simple graphics for a presentation. Instead of using complicated design software, I remembered the Turtle module in Python, a simple yet powerful way to create drawings programmatically.

In this article, I’ll share everything you need to know about Python Turtle graphics. Whether you’re a beginner looking to make your first program more visual or an experienced developer wanting to create complex animations, Turtle has something for everyone.

So let’s get started!

What is Python Turtle Graphics?

Python’s Turtle graphics is a built-in module that allows you to create pictures and shapes by programming a “turtle” to move around the screen. Inspired by the Logo programming language, it’s named after a turtle that moves around with a pen attached to its tail, drawing lines as it moves.

This module is particularly popular for teaching programming concepts to beginners because it provides immediate visual feedback. However, it’s versatile enough for creating complex graphics and even simple games.

Read Draw a Shape in Python Using Turtle

Get Started with Turtle Graphics

Let us start with the basic implementation of Turtle graphics.

Basic Setup and Commands

Let’s start with a simple example to see Turtle in action:

import turtle

# Create a turtle object
t = turtle.Turtle()

# Draw a square
for _ in range(4):
    t.forward(100)  # Move forward 100 units
    t.right(90)     # Turn right 90 degrees

# Keep the window open
turtle.mainloop()

I executed the above example code and added the screenshot below.

python turtle graphics

This code creates a square with sides of 100 units. The turtle starts at the center of the screen, moves forward, turns right 90 degrees, and repeats this four times.

Here are some basic commands to get you started:

  • forward(distance) or fd(distance): Moves the turtle forward
  • backward(distance) or bk(distance): Moves the turtle backward
  • right(angle) or rt(angle): Rotates the turtle clockwise
  • left(angle) or lt(angle): Rotates the turtle counterclockwise
  • penup() or pu(): Lifts the pen (moves without drawing)
  • pendown() or pd(): Puts the pen down (draws while moving)
  • goto(x, y): Moves the turtle to the specified coordinates

Check out Create a Snake Game in Python Using Turtle

Customize Your Turtle

You can customize how your turtle looks and behaves:

import turtle

t = turtle.Turtle()

# Customize the turtle
t.shape("turtle")       # Change the shape to a turtle
t.color("blue", "red")  # Set outline and fill colors
t.pensize(5)            # Set the line thickness
t.speed(1)              # Set the speed (1=slowest, 10=fastest, 0=instant)

# Draw a filled triangle
t.begin_fill()
for _ in range(3):
    t.forward(100)
    t.left(120)
t.end_fill()

turtle.mainloop()

I executed the above example code and added the screenshot below.

turtle graphics

Read Attach an Image in Turtle Python

Method 1: Draw Shapes and Patterns

One of the most common uses of Turtle graphics is to draw shapes and patterns. Let’s create a function to draw any regular polygon:

import turtle

def draw_polygon(sides, length):
    t = turtle.Turtle()
    t.speed(0)  # Fastest speed

    # Calculate the angle
    angle = 360 / sides

    # Draw the polygon
    for _ in range(sides):
        t.forward(length)
        t.right(angle)

    turtle.mainloop()

# Draw an octagon
draw_polygon(8, 50)

I executed the above example code and added the screenshot below.

python turtle graphics online

Let’s create something more complex – a colorful spiral:

import turtle
import random

def colorful_spiral():
    t = turtle.Turtle()
    t.speed(0)
    turtle.colormode(255)

    for i in range(200):
        # Random RGB color
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        t.pencolor(r, g, b)

        # Draw the spiral
        t.forward(i)
        t.right(91)

    turtle.mainloop()

colorful_spiral()

Check out Python Turtle Colors + Examples

Method 2: Create Interactive Drawings

Turtle also allows for interactive drawings using event handlers:

import turtle

def draw_with_mouse():
    screen = turtle.Screen()
    t = turtle.Turtle()
    t.speed(0)
    t.pensize(3)

    # Hide the turtle
    t.hideturtle()

    # Functions to handle events
    def move_to(x, y):
        t.penup()
        t.goto(x, y)
        t.pendown()

    def drag(x, y):
        t.goto(x, y)

    # Set up event handlers
    screen.onscreenclick(move_to)
    screen.ondrag(drag)

    # Start the event loop
    turtle.mainloop()

draw_with_mouse()

This creates a simple drawing program where you can click to position the turtle and drag to draw.

Read Python Turtle Speed With Examples

Method 3: Create Animations

Turtle can also be used to create simple animations:

import turtle
import time

def bouncing_ball():
    # Set up the screen
    screen = turtle.Screen()
    screen.bgcolor("black")
    screen.title("Bouncing Ball Animation")

    # Create the ball
    ball = turtle.Turtle()
    ball.shape("circle")
    ball.color("red")
    ball.penup()
    ball.speed(0)

    # Set initial position and velocity
    ball.goto(0, 200)
    x_velocity = 3
    y_velocity = 0
    gravity = -0.1

    while True:
        # Update position
        ball.goto(ball.xcor() + x_velocity, ball.ycor() + y_velocity)

        # Update velocity (apply gravity)
        y_velocity += gravity

        # Check for wall collision
        if ball.xcor() > 300 or ball.xcor() < -300:
            x_velocity *= -1

        # Check for floor collision
        if ball.ycor() < -300:
            y_velocity *= -0.9  # Bounce with energy loss

            # Stop if the bounce is too small
            if abs(y_velocity) < 0.5:
                y_velocity = 0
                ball.sety(-300)  # Ensure it stays on the floor

        # Slight delay
        time.sleep(0.02)

        # Update the screen
        screen.update()

# Set up for animation
screen = turtle.Screen()
screen.tracer(0)  # Turn off automatic updates
bouncing_ball()

Method 4: Create a Simple Game

Let’s create a simple catching game using Turtle graphics:

import turtle
import random
import time

def catch_game():
    # Set up the screen
    screen = turtle.Screen()
    screen.bgcolor("lightblue")
    screen.title("Catch the Star!")
    screen.setup(width=600, height=600)
    screen.tracer(0)

    # Create the player
    player = turtle.Turtle()
    player.shape("turtle")
    player.color("green")
    player.penup()
    player.speed(0)
    player.goto(0, -250)

    # Create the star
    star = turtle.Turtle()
    star.shape("circle")
    star.color("gold")
    star.penup()
    star.speed(0)
    star.goto(random.randint(-280, 280), 280)

    # Set up the score display
    score = 0
    score_display = turtle.Turtle()
    score_display.hideturtle()
    score_display.penup()
    score_display.goto(0, 260)
    score_display.color("black")
    score_display.write(f"Score: {score}", align="center", font=("Arial", 24, "normal"))

    # Define movement functions
    def move_left():
        x = player.xcor()
        if x > -280:
            player.setx(x - 20)

    def move_right():
        x = player.xcor()
        if x < 280:
            player.setx(x + 20)

    # Set up keyboard bindings
    screen.listen()
    screen.onkeypress(move_left, "Left")
    screen.onkeypress(move_right, "Right")

    # Game loop
    game_over = False
    star_speed = 5

    while not game_over:
        # Move the star down
        star.sety(star.ycor() - star_speed)

        # Check if the star is caught
        if (star.ycor() < -230 and star.ycor() > -270 and 
            abs(star.xcor() - player.xcor()) < 30):
            # Reset star position
            star.goto(random.randint(-280, 280), 280)
            # Increase score
            score += 1
            score_display.clear()
            score_display.write(f"Score: {score}", align="center", font=("Arial", 24, "normal"))
            # Increase difficulty
            star_speed += 0.5

        # Check if the star is missed
        elif star.ycor() < -300:
            star.goto(random.randint(-280, 280), 280)

        # Update the screen
        screen.update()
        time.sleep(0.02)

    screen.mainloop()

catch_game()

Use Turtle for Educational Purposes

Turtle graphics is an excellent tool for teaching programming concepts:

  1. Teaching loops: Drawing repetitive patterns demonstrates the power of loops
  2. Functions and modularity: Breaking down complex drawings into reusable functions
  3. Coordinates and geometry: Understanding the coordinate system and geometric principles
  4. Conditional logic: Using if statements to create dynamic behaviors

Here’s an example that combines these concepts to create a simple function-based drawing system:

import turtle

def draw_shape(shape_type, size=100, color="black", fill=False):
    t = turtle.Turtle()
    t.speed(0)
    t.color(color)

    if fill:
        t.begin_fill()

    if shape_type == "square":
        for _ in range(4):
            t.forward(size)
            t.right(90)
    elif shape_type == "circle":
        t.circle(size/2)
    elif shape_type == "triangle":
        for _ in range(3):
            t.forward(size)
            t.left(120)
    elif shape_type == "star":
        for _ in range(5):
            t.forward(size)
            t.right(144)

    if fill:
        t.end_fill()

# Create a USA-themed drawing
screen = turtle.Screen()
screen.bgcolor("white")

# Draw a red square
draw_shape("square", 200, "red", True)

# Draw a white circle inside
draw_shape("circle", 150, "white", True)

# Draw a blue star inside
draw_shape("star", 80, "blue", True)

turtle.mainloop()

This function-based approach makes it easy to create complex drawings with simple, reusable components.

Practical Applications

While Turtle graphics might seem simple, it has several practical applications:

  1. Educational visualizations: Creating visual representations of algorithms like sorting or pathfinding
  2. Data visualization: Plotting simple graphs or charts
  3. Fractals and mathematical patterns: Visualizing complex mathematical concepts
  4. Prototyping game mechanics: Testing game ideas before implementing them in more advanced frameworks

I hope you found this article helpful in understanding Python’s Turtle graphics module. It’s a versatile tool that can be both fun and educational. Whether you’re teaching programming to beginners or looking for a simple way to create visual elements in your Python projects, Turtle graphics provides an accessible entry point.

You may also read other Turtle-related articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.