Python(Turtle Module) - Mouse Cursor Position in Window

烂漫一生 提交于 2020-06-12 09:13:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/35732851/pythonturtle-module-mouse-cursor-position-in-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!