我正在开发一个小的 python gui,只是为了好玩和学习,我一直在尝试改变 Canvas 项目上的光标形状。
我知道可以在将鼠标悬停在 Canvas 小部件上时更改光标形状,在创建 Canvas 时使用 cursor="whatever"选项。但我只想对 Canvas 内的项目这样做。
这使得项目正确:
self.image_obj = canvas.create_image(
self.column_coordinate,
self.row_coordinate,
image=image
)
那行不通:
self.image_obj = canvas.create_image(
self.column_coordinate,
self.row_coordinate,
image=image,
cursor="hand1"
)
项目的“光标”选项似乎不存在,有没有办法解决这个问题?
最佳答案
更改光标的唯一方法是更改它在 Canvas 上的显示方式。通过在每次鼠标移动时检查它是否在您希望它改变的项目的边界框内,您可以实现这种效果。
from tkinter import *
canvas = Canvas(width=200,height=200)
canvas.pack()
rec = canvas.create_rectangle(100,0,200,200,fill="red")#example object
def check_hand(e):#runs on mouse motion
bbox= canvas.bbox(rec)
if bbox[0] < e.x and bbox[2] > e.x and bbox[1] < e.y and bbox[3] > e.y:#checks whether the mouse is inside the boundrys
canvas.config(cursor="hand1")
else:
canvas.config(cursor="")
canvas.bind("<Motion>",check_hand)#binding to motion
关于python - tkinter:如何更改 Canvas 项目上的光标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54605404/