Python Turtle Get Position

Recently, while teaching a Python workshop for beginners in my local coding club, I needed to create a simple game that required tracking the position of a turtle on the screen. The challenge was finding an easy way to get the turtle’s coordinates at any given moment.

Fortunately, Python’s turtle module provides several methods to retrieve position information. In this article, I’ll share the different ways you can get position data from a turtle object and how you can use this in your projects.

Let’s get in!

What is Python Turtle Position?

In the turtle module, position refers to the x and y coordinates of the turtle on a coordinate plane. The center of the screen is typically position (0,0), with:

  • x-coordinate increases as you move right
  • y-coordinate increases as you move up

Understanding how to access these coordinates is essential for many turtle applications, from simple drawings to interactive games.

Read Make a Smiling Face in Python Turtle

Method 1: Use position() Function

The simplest way to get a turtle’s current position is by using the position() function in Python.

import turtle

# Create a turtle
t = turtle.Turtle()

# Move the turtle
t.forward(100)
t.left(90)
t.forward(50)

# Get the current position
current_pos = t.position()
print(f"Current position: {current_pos}")

turtle.done()

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

get x y coordinates on click python turtle

When you run this code, the turtle will move 100 pixels forward, turn left 90 degrees, move another 50 pixels, and then print its current coordinates as a tuple (100.00, 50.00).

The position() function returns a tuple with both x and y coordinates, making it perfect when you need both values together.

Method 2: Use xcor() and ycor() Functions

If you only need one coordinate at a time, turtle provides separate functions for x and y coordinates:

import turtle

t = turtle.Turtle()

# Draw a simple shape
t.forward(75)
t.right(45)
t.forward(75)

# Get individual coordinates
x_position = t.xcor()
y_position = t.ycor()

print(f"X coordinate: {x_position}")
print(f"Y coordinate: {y_position}")

turtle.done()

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

turtle position

These functions are particularly useful when you only need to check or manipulate one axis at a time, like creating boundary detection in a game.

Check out Python Turtle Nested Loop

Method 3: Use pos() – The Alias Function

Python’s pos() function is simply an alias for position(). Some programmers prefer using this shorter name:

import turtle

t = turtle.Turtle()
t.forward(200)
t.left(30)
t.forward(100)

# Using the pos() alias
current_pos = t.pos()
print(f"Current position using pos(): {current_pos}")

turtle.done()

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

python turtle position

Both position() and pos() function the same way, so it’s just a matter of personal preference.

Get Mouse Position in Python Turtle

In interactive applications, you might want to track the position of the mouse cursor. Turtle provides this capability through event handling:

import turtle

# Setup the screen
screen = turtle.Screen()
t = turtle.Turtle()
t.speed(0)
t.hideturtle()

# Function to handle clicks
def get_mouse_position(x, y):
    print(f"Mouse clicked at: ({x}, {y})")
    t.penup()
    t.goto(x, y)
    t.pendown()
    t.dot(10, "red")  # Mark the clicked position

# Set up the click handler
screen.onclick(get_mouse_position)

# Keep the window open
turtle.mainloop()

This code creates a simple application where clicking anywhere on the screen reports the coordinates of the click and marks it with a red dot. This technique is essential for creating interactive games or drawing applications.

Read Python Turtle Draw Line

Practical Example: Create a Boundary-Checking Game

Let’s create a simple game that uses position tracking to implement boundary detection:

import turtle
import random

# Setup
screen = turtle.Screen()
screen.title("Boundary Game")
screen.bgcolor("lightblue")
screen.setup(width=600, height=600)

# Create player turtle
player = turtle.Turtle()
player.shape("turtle")
player.color("green")
player.penup()

# Set boundaries
boundary = 250

# Game variables
score = 0

# Display score
score_display = turtle.Turtle()
score_display.hideturtle()
score_display.penup()
score_display.goto(0, 260)
score_display.write(f"Score: {score}", align="center", font=("Arial", 16, "normal"))

# Functions to move the turtle
def move_up():
    player.setheading(90)
    player.forward(20)
    check_boundary()

def move_down():
    player.setheading(270)
    player.forward(20)
    check_boundary()

def move_left():
    player.setheading(180)
    player.forward(20)
    check_boundary()

def move_right():
    player.setheading(0)
    player.forward(20)
    check_boundary()

# Function to check if turtle is within boundaries
def check_boundary():
    global score
    x = player.xcor()
    y = player.ycor()

    # Check if turtle is outside boundaries
    if abs(x) > boundary or abs(y) > boundary:
        # Reset position
        player.goto(0, 0)
        score -= 5
        score_display.clear()
        score_display.write(f"Score: {score}", align="center", font=("Arial", 16, "normal"))
    else:
        score += 1
        score_display.clear()
        score_display.write(f"Score: {score}", align="center", font=("Arial", 16, "normal"))

# Set keyboard bindings
screen.listen()
screen.onkeypress(move_up, "Up")
screen.onkeypress(move_down, "Down")
screen.onkeypress(move_left, "Left")
screen.onkeypress(move_right, "Right")

# Keep the window open
turtle.mainloop()

In this game, we use the xcor() and ycor() functions to check if the turtle has moved beyond the boundary. If it has, we reset its position and deduct points. The player earns points by moving within the boundary.

Check out Python Turtle Mouse

Track Multiple Turtles

Sometimes, you might need to track the positions of multiple turtles at once, such as in collision detection:

import turtle
import random
import math

# Setup
screen = turtle.Screen()
screen.title("Multiple Turtle Tracker")
screen.bgcolor("black")

# Create turtles
t1 = turtle.Turtle()
t1.shape("turtle")
t1.color("red")
t1.penup()
t1.goto(-100, 0)

t2 = turtle.Turtle()
t2.shape("turtle")
t2.color("blue")
t2.penup()
t2.goto(100, 0)

# Function to check distance between turtles
def check_distance():
    # Get positions
    pos1 = t1.position()
    pos2 = t2.position()

    # Calculate Euclidean distance
    distance = math.sqrt((pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2)

    if distance < 50:
        return True
    return False

# Move turtles randomly
for _ in range(50):
    # Move first turtle
    t1.forward(random.randint(5, 15))
    t1.left(random.randint(-30, 30))

    # Move second turtle
    t2.forward(random.randint(5, 15))
    t2.left(random.randint(-30, 30))

    # Check if they're close
    if check_distance():
        print(f"Turtles are close! Distance: {math.sqrt((t1.xcor() - t2.xcor())**2 + (t1.ycor() - t2.ycor())**2)}")
        t1.color("yellow")
        t2.color("yellow")
    else:
        t1.color("red")
        t2.color("blue")

    # Small delay
    turtle.delay(100)

# Keep the window open
turtle.done()

This example shows how you can track the positions of multiple turtles and calculate the distance between them, which is useful for collision detection in games.

Get Position After Events

You can also get a turtle’s position after specific events, like when the turtle completes a drawing:

import turtle

t = turtle.Turtle()
t.speed(1)

# Draw a square
for _ in range(4):
    t.forward(100)
    t.right(90)
    # Get position after each side
    print(f"Position after move: {t.position()}")

# Final position should be back at the start
print(f"Final position: {t.position()}")

turtle.done()

This technique is helpful when debugging drawings or creating animations that depend on specific positions.

I hope you found this article helpful in understanding how to get position information in Python Turtle. As you can see, the position functions are straightforward to use, but they also open up many possibilities for creating interactive programs.

You may like to 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.