这个效果可以通过bind和after组合来实现。
使用bind 跟踪光标的运动,删除label
after 每 50 毫秒检查一次光标是否未移动,并使用 place 管理器显示 label。
自从bind event.x and y 导致消息的定位偶尔出现错误以来,我已经更新了答案。 (显示在左上角)
追踪到event.x event.y,因此将其替换为
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
此更新解决了问题,现在它按预期运行。
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text = "Message")
x = y = xx = yy = 0
def display(event):
global x, y
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
label.place_forget()
def check(xx, yy):
global x, y
if x == xx and y == yy:
label.place(x = x, y = y, anchor = "s")
else:
xx, yy = x, y
root.after(50, check, xx, yy)
root.bind("<Motion>", display)
root.after(10, check, xx, yy)
root.mainloop()