带参数的Python Matplotlib回调函数

use*_*887 4 python callback matplotlib button

在按钮按下的回调函数中,无论如何都要传递除"事件"之外的更多参数吗?例如,在回调函数中,我想知道按钮的文本(在这种情况下为"下一步").我怎样才能做到这一点?

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()
Run Code Online (Sandbox Code Playgroud)

Eri*_*lum 8

另一个可能更快的解决方案是使用 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()
Run Code Online (Sandbox Code Playgroud)


And*_*lev 5

要获得这一点,您可能需要将事件处理封装在类中,如官方教程中所示:

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()
Run Code Online (Sandbox Code Playgroud)