如何使用tkinter和turtle获取鼠标位置

2024-10-02 00:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试做一个程序,让我在一个tkinter窗口上使用turtle绘图。由于某些原因,我不能得到绝对的鼠标坐标。在

我已经完成了root.winfo_pointerx() - root.winfo_rootx()(和vrootx)。 我也尝试过:

def mousePos(event):
     x,y = event.x , event.y
     return x,y

我的代码:

^{pr2}$

我希望光标位于箭头的顶部,但它总是向右和向下。另外,当我向上移动鼠标时,箭头向下移动,反之亦然。在


Tags: 程序event绘图tkinterdef原因root箭头
3条回答

仔细考虑如何设置setworldcoordinate()。-500-500意味着你的世界有1000个大小,窗口大小是500。另外,鼠标指针偏离窗口根-两个绝对坐标都应该使用。你混淆了绝对坐标-鼠标指针和vrootx,两者的比例不同,所以两者之间的距离没有意义。下面的代码可能更接近您的预期。请注意,我将世界坐标设置为与鼠标指针从窗口左上角偏移的绝对坐标相匹配。在

import turtle
import tkinter as tk
root = tk.Tk()
root.title("Draw!")
cv = tk.Canvas(root, width=500,height=500)
cv.focus_set()
cv.pack(side = tk.LEFT)
pen = turtle.RawTurtle(cv)
window = pen.getscreen()

def main():
    window.setworldcoordinates(0,500,500,0)
    window.bgcolor("white")
    frame = tk.Frame(root)
    frame.pack(side = tk.RIGHT,fill=tk.BOTH)
    pointLabel = tk.Label(frame,text="Width")
    pointLabel.pack()
    print(dir(root))
    def getPosition(event):
       x = root.winfo_pointerx()-root.winfo_rootx()
       y = root.winfo_pointery()-root.winfo_rooty()
       print(x, y)
       pen.goto(x,y)
       pass
    cv.bind("<Motion>", getPosition)
    cv.pack
    tk.mainloop()
    pass

if __name__ == "__main__":
  main()
  pass

Tkinter的鼠标位置:

    import Tkinter as tk
    root = tk.Tk()

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

    root.bind('<Motion>', motion)
    root.mainloop()

海龟的鼠标位置:

^{pr2}$

希望这有帮助。在

你有一个不是你自己造成的问题。乌龟一般在画布上使用的方法是乌龟。但是turtle没有固有的“Motion”事件类型,所以您尝试使用原始的Canvas事件类型作为替代。这就是冲突。在

你自己做的一个问题是,当你在一个快速移动的事件处理程序中时,你需要首先禁用事件处理程序,在退出时重新启用。否则,事件重叠,坏事就会发生。(不谨慎的递归和其他错误。)

我已经重新编写了你的程序如下,我相信你的意图。修复方法是添加missing turtle方法,这样我们就可以留在turtle域内:

import tkinter as tk
from turtle import RawTurtle, TurtleScreen
from functools import partial

def onscreenmove(self, fun, add=None):  # method missing from turtle.py

    if fun is None:
        self.cv.unbind('<Motion>')
    else:
        def eventfun(event):
            fun(self.cv.canvasx(event.x) / self.xscale, -self.cv.canvasy(event.y) / self.yscale)

        self.cv.bind('<Motion>', eventfun, add)

def getPosition(x, y):
    screen.onscreenmove(None)  # disable events inside handler

    pen.setheading(pen.towards(x, y))
    pen.goto(x, y)

    screen.onscreenmove(getPosition)  # reenable handler on exit

root = tk.Tk()
root.title("Draw!")

cv = tk.Canvas(root, width=500, height=500)
cv.focus_set()
cv.pack(side=tk.LEFT)

screen = TurtleScreen(cv)
screen.onscreenmove = partial(onscreenmove, screen)  # install missing method

pen = RawTurtle(screen)

frame = tk.Frame(root)
frame.pack(side=tk.RIGHT, fill=tk.BOTH)

tk.Label(frame, text="Width").pack()

screen.onscreenmove(getPosition)
screen.mainloop()

相关问题 更多 >

    热门问题