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

时间:2019-07-16 14:57:36

标签: python-3.x tkinter ttk

我正在tkinter GUI中动态生成按钮。我希望这些按钮在悬停时更改其图像。如果我尝试在不将按钮作为参数传递的情况下执行此操作,则会收到错误“ AttributeError:'事件'对象没有属性'config'。如果我尝试将“ link_file”作为参数传递给“ link_button_hover”和“ link_button_mouseoff”,则当添加按钮时,它会立即运行悬停和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))

1 个答案:

答案 0 :(得分:2)

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))
相关问题