【问题标题】:Python: Add optional argument into matplotlib button on_clicked functionPython:将可选参数添加到 matplotlib 按钮 on_clicked 函数中
【发布时间】:2021-12-30 22:58:12
【问题描述】:

我做了一些这样的功能:

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()

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

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 中需要在这种情况下创建两个 on_clicked 函数?

【问题讨论】:

标签: python matplotlib button onclick arguments


【解决方案1】:

第二个代码的问题在于,当您在 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"))
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多