首页 > 解决方案 > 悬停在 Tkinter 中的动态按钮上无法正常工作

问题描述

我在 tkinter GUI 中动态生成按钮。我希望这些按钮在悬停时改变它们的图像。如果我尝试在不将按钮作为参数传递的情况下执行此操作,则会收到错误“AttributeError:“事件”对象没有属性“配置”。如果我尝试将“link_file”作为参数传递给“link_button_hover”和“link_button_mouseoff”,当添加按钮时,它会立即运行悬停和鼠标关闭功能,然后位于鼠标关闭图像上。

def link_button_hover(e):
    e.config(image=vid_link_hover_icon)

def link_button_mouseoff(e):
    e.config(image=vid_unlinked_icon)

def create_button()
    link_file = ttk.Button(new_spot_frame, text="...")
    link_file.grid(row=1,column=0)
    link_file.config(command=lambda button=link_file: open_file_dialog(button),image=vid_unlinked_icon)
    link_file.bind('<Enter>', link_button_hover)
    link_file.bind('<Leave>', link_button_mouseoff)

或者如果我尝试将按钮作为参数传递的版本:

link_file.bind('<Enter>', link_button_hover(link_file))
link_file.bind('<Leave>', link_button_mouseoff(link_file))

标签: python-3.xtkinterttk

解决方案


Event是一个具有许多描述事件的属性的对象,但您正在尝试configure它,这就是您收到错误的原因。您需要的是用来正event.widget​​确检索小部件对象:

def link_button_hover(e):
    e.widget.config(image=vid_link_hover_icon)

def link_button_mouseoff(e):
    e.widget.config(image=vid_unlinked_icon)

或者,如果您希望在绑定中将小部件作为 arg 传递,请使用lambda

link_file.bind('<Enter>', lambda e: link_button_hover(link_file))
link_file.bind('<Leave>', lambda e: link_button_mouseoff(link_file))

推荐阅读