python - tkinter 小部件跟随鼠标移动

标签 python canvas tkinter label mouseevent

我尝试使用 Canvas 创建的红色圆圈或带有“X”的黄色标签来更改鼠标尖端。

我使用了“where”函数,它捕获鼠标移动,并为我提供鼠标尖端的当前位置,因此将上述尖端之一(即红色圆圈或黄色标签)放置在mounse尖端位置。

我意识到,如果将它们放置在鼠标尖端的右侧,则不太理想,因为它会掩盖底层小部件,但让我们把它放在一边。

使用下面的代码,您会发现选定的尖端偏离了实际的鼠标尖端,而我实际上将其放置在尖端处。那么为什么会出现偏移呢?怎么了?

我还意识到放置意味着放置小部件的西北角。

此示例程序可以让您选择要使用的提示,通过单击另一个提示来切换到它。

因此,您可以看到,通过选择任一尖端形状,行为是相同的。

import tkinter as tk

def changetip(a):            # change cursor tip, arg a is not used
    global tipType
    if tipType=="red" : tipType="yellow"
    else: tipType="red"

def where(posn):                       #cursor tiop movement and colour change
   cx=posn.x_root-w.winfo_x()
   cy=posn.y_root-w.winfo_y()
   if tipType=="red":
       tipC.place(x=cx, y=cy)
       tipL.place(x=300,y=300)
   else:
       tipC.place(x=400, y=400)
       tipL.place(x=cx,y=cy)

w=tk.Tk()
w.geometry("500x500+100+100")
w.bind("<Motion>",where)        #track mouse movement

tipType="red"           # red is the canvas circle, yellow is label

# Make a cursor tip using a circle on canvas
tip_rad=10
tipC=tk.Canvas(w,width=tip_rad*2,height=tip_rad*2,highlightthickness=0,bg="green")
tip=tk.Canvas.create_oval(tipC,tip_rad/2,tip_rad/2,tip_rad/2*3,tip_rad/2*3, width=0, fill="red")
tipC.bind("<1>",changetip)

# Make a cursor tip using a label
tip_size=1
tipL=tk.Label(w,width=tip_size, height=tip_size,text="x",bg="yellow")
tipL.bind("<1>",changetip)

w.mainloop()

最佳答案

您应该忽略事件对象 (posn),并仅使用相对于主小部件 w 的像素位置。将 where 的前两行更改如下:

def where(posn):
   cx=w.winfo_pointerx() - w.winfo_rootx()
   cy=w.winfo_pointery() - w.winfo_rooty()

关于python - tkinter 小部件跟随鼠标移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44534868/

相关文章:

javascript - JIT - 将 Spacetree 保存为图像

python - Tkinter:所有单选按钮都被选中

python - 如何知道给定标题的窗口是否已经在 Tk 中打开?

python - 从调用导入的 python 文件中获取名称

python - NesC/GMP undefined symbol

javascript - 在动态创建的 Canvas 上绘制图像

python - 应该如何使用 python tkinter 的主循环来维护 Leap Motion 的监听器帧回调?

python - 如何获取与 SQLAlchemy InstrumentedAttribute 对应的属性值?

python - 根据概率向量选择 numpy 矩阵的索引

javascript - 在 JavaScript 中将 canvas 设为全局对象是一个好习惯吗?