Python Turtle OnClick: Create Graphics with Examples

Recently, I was working on a Python project that required creating interactive graphics that respond to mouse clicks. The Turtle module in Python offers a perfect solution with its onclick functionality. In this article, I’ll show you how to use Python Turtle’s onclick capabilities to create interactive graphics and games.

I’ll cover multiple methods with practical examples that you can use in your projects.

So let’s get in!

What is Python Turtle OnClick?

The onclick method in Python’s Turtle module allows you to bind a function to a mouse click event. This means you can make your turtle graphics interactive, responding when a user clicks on the screen.

This functionality opens up possibilities for creating interactive games, educational tools, and responsive graphics.

Method 1: Basic OnClick Functionality

Let’s start with a simple example of how the onclick method works:

import turtle

# Create a screen and a turtle
screen = turtle.Screen()
t = turtle.Turtle()
t.shape("turtle")
t.color("green")

# Define a function to handle the click
def handle_click(x, y):
    t.penup()
    t.goto(x, y)
    t.pendown()
    t.circle(30)

# Bind the function to the mouse click event
screen.onclick(handle_click)

# Keep the window open
turtle.mainloop()

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

turtle onclick

In this example, whenever you click on the screen, the turtle will move to that position and draw a circle. This is a basic but powerful demonstration of the onclick functionality.

The handle_click function automatically receives the x and y coordinates of where the mouse was clicked.

Method 2: Multiple Turtles with Different Click Behaviors

You can create multiple turtles that respond differently to clicks:

import turtle

screen = turtle.Screen()
screen.setup(600, 400)
screen.title("Click on a Turtle")

# Create the first turtle - draws squares
square_turtle = turtle.Turtle()
square_turtle.shape("turtle")
square_turtle.color("blue")
square_turtle.penup()
square_turtle.goto(-150, 0)

# Create the second turtle - draws stars
star_turtle = turtle.Turtle()
star_turtle.shape("turtle")
star_turtle.color("red")
star_turtle.penup()
star_turtle.goto(150, 0)

# Function for drawing a square
def draw_square(x, y):
    square_turtle.penup()
    square_turtle.goto(x, y)
    square_turtle.pendown()
    for _ in range(4):
        square_turtle.forward(50)
        square_turtle.left(90)

# Function for drawing a star
def draw_star(x, y):
    star_turtle.penup()
    star_turtle.goto(x, y)
    star_turtle.pendown()
    for _ in range(5):
        star_turtle.forward(50)
        star_turtle.right(144)

# Bind click events to specific turtles
square_turtle.onclick(draw_square)
star_turtle.onclick(draw_star)

turtle.mainloop()

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

turtle exit on click

This example creates two turtles that respond differently when clicked. The blue turtle draws squares, while the red turtle draws stars. This demonstrates how you can assign different behaviors to different objects on your screen.

Read Python Turtle Clock

Method 3: Create Interactive Buttons

We can use Turtle’s onclick to create clickable buttons:

import turtle

screen = turtle.Screen()
screen.setup(600, 400)
screen.title("Turtle Button Example")

# Create a function to generate a button
def create_button(x, y, width, height, color, label, action):
    button = turtle.Turtle()
    button.hideturtle()
    button.penup()
    button.goto(x - width/2, y - height/2)
    button.pendown()

    # Draw the button
    button.fillcolor(color)
    button.begin_fill()
    for _ in range(2):
        button.forward(width)
        button.left(90)
        button.forward(height)
        button.left(90)
    button.end_fill()

    # Add the label
    button.penup()
    button.goto(x, y - 10)
    button.color("white")
    button.write(label, align="center", font=("Arial", 14, "bold"))

    # Define the click area
    def check_click(x_click, y_click):
        if (x - width/2) <= x_click <= (x + width/2) and (y - height/2) <= y_click <= (y + height/2):
            action()

    return check_click

# Create a drawing turtle
drawer = turtle.Turtle()
drawer.hideturtle()
drawer.penup()
drawer.goto(0, 50)
drawer.pendown()

# Button actions
def draw_circle():
    drawer.clear()
    drawer.penup()
    drawer.goto(0, 50)
    drawer.pendown()
    drawer.circle(50)

def draw_square():
    drawer.clear()
    drawer.penup()
    drawer.goto(-50, 0)
    drawer.pendown()
    for _ in range(4):
        drawer.forward(100)
        drawer.left(90)

def clear_screen():
    drawer.clear()

# Create three buttons
circle_button = create_button(-150, -100, 100, 50, "blue", "Circle", draw_circle)
square_button = create_button(0, -100, 100, 50, "green", "Square", draw_square)
clear_button = create_button(150, -100, 100, 50, "red", "Clear", clear_screen)

# Handle screen clicks
def handle_click(x, y):
    circle_button(x, y)
    square_button(x, y)
    clear_button(x, y)

screen.onclick(handle_click)

turtle.mainloop()

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

turtle.onclick

This example creates three buttons that draw different shapes when clicked. It demonstrates how to build interactive UI elements using Turtle graphics.

Check out Python Clear Turtle

Method 4: Create a Simple Game with OnClick

Let’s create a simple target-shooting game using onclick:

import turtle
import random
import time

# Set up the screen
screen = turtle.Screen()
screen.setup(600, 600)
screen.title("Target Practice Game")
screen.bgcolor("sky blue")

# Score display
score_display = turtle.Turtle()
score_display.hideturtle()
score_display.penup()
score_display.goto(0, 260)
score = 0

# Target turtle
target = turtle.Turtle()
target.shape("circle")
target.color("red")
target.shapesize(2)
target.penup()

# Timer display
timer_display = turtle.Turtle()
timer_display.hideturtle()
timer_display.penup()
timer_display.goto(0, 230)

# Update the score
def update_score():
    score_display.clear()
    score_display.write(f"Score: {score}", align="center", font=("Arial", 24, "bold"))

# Move the target to a random position
def move_target():
    x = random.randint(-250, 250)
    y = random.randint(-250, 200)
    target.goto(x, y)

# Handle clicking on the target
def hit_target(x, y):
    global score
    # Calculate distance between click and target
    distance = target.distance(x, y)
    # If click is close enough to target
    if distance < 40:  # Target size plus some margin
        score += 1
        update_score()
        move_target()

# Bind click event to target
target.onclick(hit_target)

# Game start function
def start_game():
    global score
    score = 0
    update_score()

    # Set game time (in seconds)
    game_time = 30
    start_time = time.time()

    # Move target to initial position
    move_target()

    # Game loop
    while time.time() - start_time < game_time:
        remaining = int(game_time - (time.time() - start_time))
        timer_display.clear()
        timer_display.write(f"Time: {remaining}s", align="center", font=("Arial", 18, "normal"))
        screen.update()

    # Game over
    target.hideturtle()
    timer_display.clear()
    timer_display.write("Game Over!", align="center", font=("Arial", 18, "normal"))

# Start the game
start_game()

turtle.mainloop()

This game creates a target that moves to a random position each time you successfully click on it. It demonstrates how to combine onclick with game mechanics.

Read Fractal Python Turtle

Method 5: Interactive Drawing Application

Let’s create a simple drawing application where different colors can be selected by clicking:

import turtle

# Set up the screen
screen = turtle.Screen()
screen.setup(800, 600)
screen.title("Drawing App")

# Create a drawing turtle
pen = turtle.Turtle()
pen.pensize(3)
pen.speed(0)

# Create color selection turtles
colors = ["red", "orange", "yellow", "green", "blue", "purple", "black"]
color_turtles = []

for i, color in enumerate(colors):
    t = turtle.Turtle()
    t.shape("circle")
    t.color(color)
    t.penup()
    t.goto(-300 + i * 100, -250)
    t.color_name = color  # Store the color name as an attribute
    color_turtles.append(t)

# Drawing state
drawing = False

# Function to start drawing
def start_drawing(x, y):
    global drawing
    # Only start drawing if we're not in the color selection area
    if y > -230:
        drawing = True
        pen.penup()
        pen.goto(x, y)
        pen.pendown()

# Function to stop drawing
def stop_drawing(x, y):
    global drawing
    drawing = False

# Function to draw when mouse is moved
def draw(x, y):
    if drawing and y > -230:  # Don't draw in the color selection area
        pen.goto(x, y)

# Function to change color when a color turtle is clicked
def change_color(t):
    def set_color(x, y):
        pen.color(t.color_name)
    return set_color

# Bind events
screen.onscreenclick(start_drawing, 1)  # Left mouse button
screen.onscreenclick(stop_drawing, 3)   # Right mouse button
screen.onmove(draw)

# Bind color selection
for t in color_turtles:
    t.onclick(change_color(t))

turtle.mainloop()

This drawing application lets you draw on the screen and select different colors by clicking on the color circles at the bottom. It demonstrates how to combine onclick with onmove and multiple interactive elements.

Python Turtle’s onclick functionality provides a great way to make your graphics interactive. You can use it to create games, educational tools, or any other application where user input is needed.

The key is to understand how to bind functions to click events and how to use the coordinates provided by the onclick method to determine what action to take.

You may also read:

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.