You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为仅含CTkImage的CustomTkinter按钮添加ToolTip?

解决仅含图像的CTkButton使用tktooltip报错的问题

问题描述

使用tktooltip库给仅包含CTkImage的CustomTkinter按钮添加提示框时,触发如下错误:

AttributeError: 'NoneType' object has no attribute 'bind'

设置text=" "可使功能正常,但会导致按钮形状变形,需找到无需添加空白文本即可为图像按钮添加提示框的方案。

复现代码

import customtkinter
from PIL import Image
from tktooltip import ToolTip

root = customtkinter.CTk()

icon = customtkinter.CTkImage(dark_image=Image.open("icon.png"))
button = customtkinter.CTkButton(master=root, width=10, height=10, text="", image=icon)
button.pack(pady=20, padx=20)

ToolTip(button, msg="A message", delay=0, follow=True,
        parent_kwargs={"bg": "black", "padx": 3, "pady": 3},
        fg="white", bg="orange", padx=7, pady=7)

root.mainloop()

报错详情

Traceback (most recent call last):
  File "d:\Python Projects\main.py", line 10, in <module>
    ToolTip(button, msg="A message", delay=0, follow=True,
  File "D:\Python311\Lib\site-packages\tktooltip\tooltip.py", line 83, in __init__ 
    self.widget.bind("<Enter>", self.on_enter, add="+")
  File "D:\Python311\Lib\site-packages\customtkinter\windows\widgets\ctk_button.py", line 544, in bind
    self._text_label.bind(sequence, command, add=True)
    ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'bind'

解决方法

错误原因是:当CTkButton未设置text时,内部的_text_label为None,而CTkButton的bind方法会尝试将事件绑定到_text_label,从而触发报错。

直接将ToolTip绑定到CTkButton内部负责显示图像的_image_label部件即可解决问题,该部件在仅显示图像时是有效的tkinter widget,可正常绑定事件。

修改后的代码如下:

import customtkinter
from PIL import Image
from tktooltip import ToolTip

root = customtkinter.CTk()

icon = customtkinter.CTkImage(dark_image=Image.open("icon.png"))
button = customtkinter.CTkButton(master=root, width=10, height=10, text="", image=icon)
button.pack(pady=20, padx=20)

# 绑定到按钮内部的图像标签部件
ToolTip(button._image_label, msg="A message", delay=0, follow=True,
        parent_kwargs={"bg": "black", "padx": 3, "pady": 3},
        fg="white", bg="orange", padx=7, pady=7)

root.mainloop()

此方案无需添加空白文本,不会改变按钮原有形状,同时能正常显示提示框。

内容的提问来源于stack exchange,提问作者duruburak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 19:30:54