如何为仅含CTkImage的CustomTkinter按钮添加ToolTip?
问题描述
使用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
相关产品推荐
相关产品推荐

