How to convert window coords into turtle coords (Python Turtle)

Question:

I am trying to create a program to move the turtle to where the mouse is.
I am doing:

import turtle
t = turtle.Turtle()

canvas = turtle.getcanvas()

while True:
    mouseX, mouseY = canvas.winfo_pointerxy()
    t.goto(mouseX, mouseY)

but the turtle keeps moving off the screen.
I read from this question that canvas.winfo_pointerxy() returns ‘window coordinates’ (0, 0 at the top left of the window) and that I need to convert them to ‘turtle coordinates’ (0, 0 at the center of the window) but I don’t know how to do that.

Asked By: sbottingota

||

Answers:

Can you try this?

import turtle

# create a turtle and set its speed
t = turtle.Turtle()
t.speed(3)

# create a turtle screen and set its background color
screen = turtle.Screen()
screen.bgcolor('white')

# infinite loop to move the turtle in response to the mouse
while True:
    mouseX, mouseY = screen.onclick()
    t.goto(mouseX, mouseY)
    # add a delay to slow down the turtle's movement
    t.delay(100)

# keep the turtle window open
turtle.mainloop()

This code creates a turtle and a turtle screen, sets the screen’s background color, and defines an infinite loop that moves the turtle to the coordinates of wherever the user clicks. The mainloop() function is called at the end of the script to keep the turtle window open and allow the user to interact with the turtle. Hope this helps.

Answered By: FreddyNoNose

First, you need to find the size of the canvas. for this example, I used a set width and height, but for your purposes, you may find it easier to find the size instead of entering it.

    width = 500
    height = 300

    t = turtle.Turtle()
    canvas = turtle.getcanvas()
    turtle.screensize(canvwidth=width, canvheight=height)

you can use this code to find the width and height

    width = canvas.winfo_width()
    height = canvas.winfo_height()

When you measure the mouse’s position, however, you’ll need to do this calculation to get the right value.

    mouseX = canvas.winfo_pointerx() - width/2
    mouseY = (canvas.winfo_pointery()*-1) + height/2
    t.goto(mouseX, mouseY)
Answered By: Jon Mab

You have to use the dimensions of the window to calculate the center of the window. You just need to subtract the midpoint from the mouse coordinates (since the 0,0 for that is the top-left of the screen) to get it.

You need to add the following:

width = canvas.winfo_width()
height = canvas.winfo_height()

midpoint_x = width / 2
midpoint_y = height / 2

turtleX = mouseX - midpoint_x
turtleY = mouseY - midpoint_y

You end up with something like this:

import turtle

t = turtle.Turtle()
canvas = turtle.getcanvas()
width = canvas.winfo_width()
height = canvas.winfo_height()
midpoint_x = width / 2
midpoint_y = height / 2

while True:
    mouseX, mouseY = canvas.winfo_pointerxy()

    turtleX = mouseX - midpoint_x
    turtleY = mouseY - midpoint_y

    t.goto(turtleX, turtleY)
Answered By: coniferous