悬停在 Tkinter 中的动态按钮上无法正常工作

天尼士

我在 tkinter GUI 中动态生成按钮。我希望这些按钮在悬停时改变它们的图像。如果我尝试在不将按钮作为参数传递的情况下执行此操作,则会收到错误 'AttributeError: 'Event' object has no attribute 'config'。如果我尝试将 'link_file' 作为参数传递给 'link_button_hover' 和 'link_button_mouseoff',当按钮被添加时,它会立即运行 hover 和 mouseoff 函数,然后位于 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))
亨利·伊克

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))

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章