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:
This is the extent to which the turtle goes if my mouse is on the edge of the screen

Asked By: sbottingota

||

Answers:

This happens for 2 reasons:

  1. canvas.winfo_pointerxy() gives you the mouse coordinates relative to your screen, not the canvas
  2. 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)
Answered By: Christian Patzl
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.