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.
Asked
Active
Viewed 1.1k times
2
-
Are you using Python's [`turtle`](https://docs.python.org/library/turtle.html) module? If so, have you had a look at ["Using Events"](https://docs.python.org/2/library/turtle.html#using-events) in the documentation? – das-g Mar 01 '16 at 20:57
-
Yes. It only has events for onClick, click drag, on click release. I need it to listen for the location of the mouse pointer. – helpneeded92 Mar 01 '16 at 22:24
-
Getting the mouse coordinates in the turtle screen is all i ask. So i can make the turtle rotate and look at the mouse. – helpneeded92 Mar 01 '16 at 22:31
2 Answers
6
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.
-2
I do not know
print("I do not know")
BOB guy
- 1
-
As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 29 '22 at 09:22