user3092887 user3092887 - 1 month ago 6
Python Question

Python Matplotlib callback function with parameters

In a callback function of button presses, is there anyway to pass more parameters other than 'event'? For example, in the call back function, I want to know the text of the button ('Next' in this case). How can I do that?

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

Answer

To obtain that, you might need to encapsulate event processing in a class, as in 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()