光标跟踪 Python Tkinter
Cursor Tracking Python Tkinter
我正在创建国际象棋,我遇到的第一个问题是实现创建代码,该代码将允许我获取鼠标的当前位置并在该鼠标坐标中打印该鼠标图像并基本上循环它直到用户这么说。现在它只是一个计时器。随意用另一个 gif 替换图像。这只是部分代码
我不知道还能尝试什么。我基本上重新安排了代码,希望那是问题所在,但事实并非如此。
def Mousecoords():
pointxy = root.winfo_pointerxy()
print(str(pointxy))
canvas.create_image(pointxy[0], pointxy[1], image=whiteKing.pieceImage)
time.sleep(0.3)
ok = 0
while ok <= 10:
root.after(500, Mousecoords)
ok += 1
现在,代码所做的是实时获取光标的实际坐标,并且在整个计时器持续时间内这样做之后,它会显示图像,但是,我想要实现的是得到坐标和图像被模拟打印出来。
现在,它的作用是:
获取坐标(1)
获取坐标 (2)
获取坐标 (3)
获取坐标 (4)
获取坐标 (5)
获取坐标 (6)
获取坐标 (7)
获取坐标 (8)
获取坐标 (9)
获取坐标 (10)
打印图像(同时打印 1-10 张)
相反,我想要它做的是:
获取坐标(1)
在 (1) 处显示图像
获取坐标 (2)
在 (2) 处显示图像
获取坐标 (3)
在 (3) 处显示图像
获取坐标 (4)
在 (4) 处显示图像
获取坐标 (5)
在 (5) 处显示图像
获取坐标 (6)
在 (6) 处显示图像
获取坐标 (7)
在 (7) 处显示图像
获取坐标 (8)
在 (8) 处显示图像
获取坐标 (9)
在 (9) 处显示图像
获取坐标 (10)
在 (10)
处显示图像
如果有其他方法让图片跟随光标,请赐教谢谢
也请告诉我,如果我没有解释清楚或遗漏了一些位
您不应使用 winfo_pointerxy()
,因为它 returns 鼠标位置相对于屏幕原点(屏幕左上角)。在 canvas 上使用 bind('<Motion>', callback)
来跟踪鼠标相对于 canvas 的位置(那么您不需要使用 .after()
)。另外,你不应该每次想更新图像时都重新创建图像,你应该更新图像的坐标。
下面是示例代码:
from tkinter import *
from PIL import Image, ImageTk
def Mousecoords(event):
pointxy = (event.x, event.y) # get the mouse position from event
print(pointxy)
canvas.coords(cimg, pointxy) # move the image to mouse postion
root = Tk()
img = ImageTk.PhotoImage(file='_red.png')
canvas = Canvas(width=400, height=200)
cimg = canvas.create_image(200, 100, image=img)
canvas.pack()
canvas.bind('<Motion>', Mousecoords) # track mouse movement
root.mainloop()
并且输出:
我正在创建国际象棋,我遇到的第一个问题是实现创建代码,该代码将允许我获取鼠标的当前位置并在该鼠标坐标中打印该鼠标图像并基本上循环它直到用户这么说。现在它只是一个计时器。随意用另一个 gif 替换图像。这只是部分代码
我不知道还能尝试什么。我基本上重新安排了代码,希望那是问题所在,但事实并非如此。
def Mousecoords():
pointxy = root.winfo_pointerxy()
print(str(pointxy))
canvas.create_image(pointxy[0], pointxy[1], image=whiteKing.pieceImage)
time.sleep(0.3)
ok = 0
while ok <= 10:
root.after(500, Mousecoords)
ok += 1
现在,代码所做的是实时获取光标的实际坐标,并且在整个计时器持续时间内这样做之后,它会显示图像,但是,我想要实现的是得到坐标和图像被模拟打印出来。
现在,它的作用是:
获取坐标(1) 获取坐标 (2) 获取坐标 (3) 获取坐标 (4) 获取坐标 (5) 获取坐标 (6) 获取坐标 (7) 获取坐标 (8) 获取坐标 (9) 获取坐标 (10)
打印图像(同时打印 1-10 张)
相反,我想要它做的是:
获取坐标(1) 在 (1) 处显示图像 获取坐标 (2) 在 (2) 处显示图像 获取坐标 (3) 在 (3) 处显示图像 获取坐标 (4) 在 (4) 处显示图像 获取坐标 (5) 在 (5) 处显示图像 获取坐标 (6) 在 (6) 处显示图像 获取坐标 (7) 在 (7) 处显示图像 获取坐标 (8) 在 (8) 处显示图像 获取坐标 (9) 在 (9) 处显示图像 获取坐标 (10) 在 (10)
处显示图像如果有其他方法让图片跟随光标,请赐教谢谢 也请告诉我,如果我没有解释清楚或遗漏了一些位
您不应使用 winfo_pointerxy()
,因为它 returns 鼠标位置相对于屏幕原点(屏幕左上角)。在 canvas 上使用 bind('<Motion>', callback)
来跟踪鼠标相对于 canvas 的位置(那么您不需要使用 .after()
)。另外,你不应该每次想更新图像时都重新创建图像,你应该更新图像的坐标。
下面是示例代码:
from tkinter import *
from PIL import Image, ImageTk
def Mousecoords(event):
pointxy = (event.x, event.y) # get the mouse position from event
print(pointxy)
canvas.coords(cimg, pointxy) # move the image to mouse postion
root = Tk()
img = ImageTk.PhotoImage(file='_red.png')
canvas = Canvas(width=400, height=200)
cimg = canvas.create_image(200, 100, image=img)
canvas.pack()
canvas.bind('<Motion>', Mousecoords) # track mouse movement
root.mainloop()
并且输出: