user3092887
user3092887

Reputation: 501

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

Upvotes: 7

Views: 6577

Answers (2)

Eric Blum
Eric Blum

Reputation: 784

Another possibly quicker solution is to use a lambda function:

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

Upvotes: 9

Andrey Sobolev
Andrey Sobolev

Reputation: 12713

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

Upvotes: 6

Related Questions