Python:将可选参数添加到matplotlib按钮_单击的函数中



我做了一些类似的函数:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button
def clicked(event):
print("Button pressed")
button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
b1 = Button(button_pos, 'Button1')
b1.on_clicked(clicked)
button_pos = plt.axes([0.2, 0.8, 0.1, 0.075])
b2 = Button(button_pos, 'Button2')
b2.on_clicked(clicked)
plt.show()

我现在的目标是在点击函数中添加第二个参数。该函数现在具有以下形式:

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')
b1.on_clicked(clicked(text=" its the first"))
button_pos = plt.axes([0.2, 0.8, 0.1, 0.075])
b2 = Button(button_pos, 'Button2')
b2.on_clicked(clicked)
b2.on_clicked(clicked(text=" its the second"))
plt.show()

但有了这个改变,我得到了以下错误消息:

Traceback (most recent call last):
File "/bla/main.py", line 24, in <module>
b1.on_clicked(clicked(text=" its the first"))
TypeError: clicked() missing 1 required positional argument: 'event'

他们是在这样的函数中放置第二个参数的方法吗?还是在这种情况下,Python需要生成两个点击的函数?

第二个代码的问题是,当您在b1.on_clicked内部使用函数clicked时,您正在调用它。这会引发错误。

相反,b1.on_clicked将一个函数作为参数,然后在后台调用该函数,将事件作为参数传递。

你可以这样做

def fn_maker(text=''):
def clicked(event):
print(f"Button pressed{text}")
return clicked
button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
b1 = Button(button_pos, 'Button1')
b1.on_clicked(fn_maker(text=" its the first"))
...

最新更新