Why is the turtle offset?
Question:
I am trying to create a program to move the turtle to where the mouse is.
Right now I am doing:
import turtle
t = turtle.Turtle()
canvas = turtle.getcanvas()
width = canvas.winfo_width()
height = canvas.winfo_height()
midpointX = width / 2
midpointY = height / 2
t.speed(0)
while True:
mouseX, mouseY = canvas.winfo_pointerxy()
turtleX = mouseX - midpointX
turtleY = (mouseY - midpointY) * -1
t.goto(turtleX, turtleY)
The turtle is offset when I run it in PyCharm or through the command line, but not when I run it on replit.
I am using Windows 11 if that helps.
This is the extent to which the turtle goes if my mouse is on the edge of the screen:
Answers:
This happens for 2 reasons:
- canvas.winfo_pointerxy() gives you the mouse coordinates relative to your screen, not the canvas
- When you resize the window, width and height don’t change because they’re just stored values from the beginning
You can fix this by moving midpointX and midpointY inside the loop and using canvas.winfo_rootx(), which gives you the position on the screen:
import turtle
t = turtle.Turtle()
canvas = turtle.getcanvas()
t.speed(0)
while True:
mouseX, mouseY = canvas.winfo_pointerxy()
midpointX = canvas.winfo_width() / 2
midpointY = canvas.winfo_height() / 2
turtleX = mouseX - midpointX - canvas.winfo_rootx()
turtleY = -mouseY + midpointY + canvas.winfo_rooty()
t.goto(turtleX, turtleY)
I am trying to create a program to move the turtle to where the mouse is.
Right now I am doing:
import turtle
t = turtle.Turtle()
canvas = turtle.getcanvas()
width = canvas.winfo_width()
height = canvas.winfo_height()
midpointX = width / 2
midpointY = height / 2
t.speed(0)
while True:
mouseX, mouseY = canvas.winfo_pointerxy()
turtleX = mouseX - midpointX
turtleY = (mouseY - midpointY) * -1
t.goto(turtleX, turtleY)
The turtle is offset when I run it in PyCharm or through the command line, but not when I run it on replit.
I am using Windows 11 if that helps.
This is the extent to which the turtle goes if my mouse is on the edge of the screen:
This happens for 2 reasons:
- canvas.winfo_pointerxy() gives you the mouse coordinates relative to your screen, not the canvas
- When you resize the window, width and height don’t change because they’re just stored values from the beginning
You can fix this by moving midpointX and midpointY inside the loop and using canvas.winfo_rootx(), which gives you the position on the screen:
import turtle
t = turtle.Turtle()
canvas = turtle.getcanvas()
t.speed(0)
while True:
mouseX, mouseY = canvas.winfo_pointerxy()
midpointX = canvas.winfo_width() / 2
midpointY = canvas.winfo_height() / 2
turtleX = mouseX - midpointX - canvas.winfo_rootx()
turtleY = -mouseY + midpointY + canvas.winfo_rooty()
t.goto(turtleX, turtleY)