0

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.

sbottingota
  • 533
  • 1
  • 3
  • 18
  • Did you check out [this answer](https://stackoverflow.com/a/72841893/6243352) from the linked thread that shows the conversion and provides a complete, runnable example? – ggorlen Dec 13 '22 at 17:38

2 Answers2

0

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)
Jon Mab
  • 18
  • 5
0

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)
coniferous
  • 67
  • 8