python-3.x - 悬停在 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))
解决方案
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))
推荐阅读
- java - 将此代码从 C# 转换为 Java,还有什么可以在 Java 中简化的吗?
- excel - ComboBox 不接受字符,但接受数值
- java - 如何通过java springboot使用聚合项目操作从文档中排除嵌套字段
- javascript - 节点js服务器端的多字段输入请求
- excel - 我无法合并到 AA 列
- c# - 从第三方网站重定向回 wpf 应用程序
- python - MLP的Hessian矩阵wrt参数不对称(TF2.0)
- javascript - 如何使用 javascript 获取已安装的 chrome 扩展列表
- python - 如何通过以元组为参数的函数比较两个变量?
- asp.net - Excel下载未从服务器发生