turtle - How to get mouse cursor position in window?

10,309

turtle.getcanvas() returns a Tkinter Canvas.

Like with a Tkinter window, you can get the current mouse pointer coordinates by winfo_pointerx and .winfo_pointery on it:

canvas = turtle.getcanvas()
x, y = canvas.winfo_pointerx(), canvas.winfo_pointery()
# or
# x, y = canvas.winfo_pointerxy()

If you want to only react to movement instead of e.g. polling mouse pointer positions in a loop, register an event:

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

canvas = turtle.getcanvas()
canvas.bind('<Motion>', motion)

Note that events only fire while the mouse pointer hovers over the turtle canvas.

All these coordinates will be window coordinates (with the origin (0, 0) at the top left of the turtle window), not turtle coordinates (with the origin (0, 0) at the canvas center), so if you want to use them for turtle positioning or orientation, you'll have to do some transformation.

Share:
10,309
helpneeded92
Author by

helpneeded92

Updated on June 13, 2022

Comments

  • helpneeded92
    helpneeded92 almost 2 years

    How would I go about finding the current position of the mouse pointer in the turtle screen? I want it so I have the mouse position before I click and while im moving the cursor. I have searched google and this website can't find anything besides how to get the position after a click.