如何获取Tkinter按钮组件绑定的全部回调函数列表?
在Tkinter中获取组件绑定的回调函数列表
可以实现,但Tkinter没有提供公开的官方API直接获取,需要访问组件的内部属性来提取。下面分两种场景说明:
1. 获取通过bind()绑定的事件回调
Tkinter组件内部维护了一个_bindings字典,键是事件类型(比如<Button-1>),值是该事件绑定的所有回调元组列表。每个元组包含回调函数、附加参数等信息,我们可以从中提取函数名。
示例代码:
# 获取<Button-1>事件的所有绑定回调 bind_callbacks = button._bindings.get("<Button-1>", []) bind_func_names = [cb[0].__name__ for cb in bind_callbacks] print(bind_func_names) # 输出: ['hi', 'salutations', 'and_so_forth']
2. 获取通过command参数设置的回调
Button的command是组件的配置选项,可以用cget()方法获取对应的函数对象,再提取其名称:
command_func = button.cget("command") command_func_name = command_func.__name__ if command_func else None print(command_func_name) # 输出: 'bye'
合并所有回调函数名
把两部分结果合并,就能得到你期望的列表:
all_func_names = bind_func_names + [command_func_name] print(tuple(all_func_names)) # 输出: ('hi', 'salutations', 'and_so_forth', 'bye')
补充说明
你之前尝试的方法无效的原因:
button.command.get()/button.command.cget():错误的调用方式,command是组件配置项,必须通过button.cget("command")获取button.invoke():仅触发command绑定的回调,不会返回所有绑定的函数列表
完整测试代码:
import tkinter as tk def hi(event): print('hello') return hi def bye(): print('bye') return bye def salutations(event): print('... and salutations...') return bye def and_so_forth(event): print('... and so forth...') return bye root = tk.Tk() button = tk.Button(root, text='test', command = bye) button.bind("<Button-1>", hi) button.bind("<Button-1>", salutations, "+") button.bind("<Button-1>", and_so_forth, "+") # 获取所有绑定的回调函数名 bind_callbacks = button._bindings.get("<Button-1>", []) bind_func_names = [cb[0].__name__ for cb in bind_callbacks] command_func = button.cget("command") command_func_name = command_func.__name__ if command_func else None all_func_names = tuple(bind_func_names + [command_func_name]) print(all_func_names) # ('hi', 'salutations', 'and_so_forth', 'bye') button.pack() root.mainloop()
内容的提问来源于stack exchange,提问作者no-one
相关产品推荐
相关产品推荐

