Python如何为matplotlib Button的on_clicked回调函数添加额外参数
你遇到的报错是因为on_clicked方法需要传入未执行的可调用对象,你写clicked(text=" its the first")会在代码运行到这一行时直接调用clicked函数,此时还没有触发点击事件,无法传入event参数,自然会抛出参数缺失的错误。
你不需要为每个按钮单独写处理函数,有两种常用的方式可以给回调传入自定义参数:
- 方法1:使用lambda匿名函数做一层包装,接收框架传入的event参数后再调用你自定义的回调,同时传入额外参数
- 方法2:使用
functools.partial预绑定自定义参数,生成新的可调用对象传给on_clicked
以下是修正后的可用代码(使用lambda方案,写法更简洁):
import matplotlib.pyplot as plt from matplotlib.widgets import Button def clicked(event, text): print("Button pressed"+text) button_pos = plt.axes([0.2, 0.9, 0.1, 0.075]) b1 = Button(button_pos, 'Button1') # lambda接收event参数,再传递给clicked函数,同时传入自定义的text b1.on_clicked(lambda event: clicked(event, text=" its the first")) button_pos = plt.axes([0.2, 0.8, 0.1, 0.075]) b2 = Button(button_pos, 'Button2') b2.on_clicked(lambda event: clicked(event, text=" its the second")) plt.show()
如果用partial方案,只需要修改绑定部分的代码即可:
from functools import partial # 其余代码不变 b1.on_clicked(partial(clicked, text=" its the first")) b2.on_clicked(partial(clicked, text=" its the second"))
内容的提问来源于stack exchange,提问作者Martin Kunze
相关产品推荐
相关产品推荐

