将鼠标悬停在python tkinter窗口上时如何将自定义图像添加到光标

问题描述

当光标悬停在我的 tkinter 窗口上时,我想制作一个自定义图像光标,如下所示:

Black cursor

然而,无论我如何用谷歌搜索,我都无法找到如何将自定义光标添加到我的 tkinter 窗口,所以我坚持使用认的白色光标。

Default cursor

当光标悬停在我的 tkinter 窗口上时,是否可以将自定义图像添加到我的光标?

解决方法

我假设您已经有一个自定义图像并且它是一个 .cur 文件,如果没有,它应该是 curanixbm 文件,其中是唯一受支持的游标扩展。获得文件后,您可以使用主窗口的 cursor 选项指定它,例如:

from tkinter import *

root = Tk()
path = '@Norm.ani' # Path to the image followed by @
root['cursor'] = path # Set the cursor 

Button(root,text='Anything').pack(padx=10,pady=10) # Demo button to show cursor

root.mainloop()

这会将光标应用于整个窗口,尽管有些小部件无法应用自定义光标,例如 Menu

如果您只想为一个小部件自定义光标,请使用该小部件的光标选项,例如:

Button(root,text='Anything',cursor=path).pack(padx=10,pady=10) # Applies JUST to button

为什么要使用“@”?

来自文档:

“使用字符串 '@' 后跟 .xbm 文件的路径名代替标准位图名称。”。

就您而言,anicur 文件。