带参数的Python Matplotlib回调函数

2024-04-28 19:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

在按钮按下的回调函数中,除了“event”之外,还有没有传递更多的参数?例如,在回调函数中,我想知道按钮的文本(在本例中为“Next”)。我怎么能做到呢?在

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

fig = plt.figure()
def next(event):
    # I want to print the text label of the button here, which is 'Next'
    pass


axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(next)
plt.show()

Tags: the函数文本importevent参数matplotlibbutton
2条回答

要获得该值,您可能需要将事件处理封装在一个类中,如official tutorial

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

class ButtonClickProcessor(object):
    def __init__(self, axes, label):
        self.button = Button(axes, label)
        self.button.on_clicked(self.process)

    def process(self, event):
        print self.button.label

fig = plt.figure()

axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = ButtonClickProcessor(axnext, "Next")

plt.show()

另一个可能更快的解决方案是使用lambda函数:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

fig = plt.figure()
def next(event, text):
    print(text)
    pass


axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(lambda x: next(x, bnext.label.get_text()))
plt.show()

相关问题 更多 >