1

If I define a Button click handler inside a function, it doesn't work. In the following example figures f1 and f2 look the same, but only if I press the button on f2, it produces output.

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

def handler(*args, **kwargs):
    print('handled')

def testfn():
    f1 = plt.figure('f1')
    b1 = Button(f1.add_axes([0.4, 0.3, 0.1, 0.04]), 'Click!')
    b1.on_clicked(handler)

f2 = plt.figure('f2')
b2 = Button(f2.add_axes([0.4, 0.3, 0.1, 0.04]), 'Click!')
b2.on_clicked(handler)

testfn()

plt.show()

1 Answer 1

7

As the documentation tells about just any widget,

For the button to remain responsive you must keep a reference to it.

You hence need to return the button from the function to keep the reference to it (button = testfn()), otherwise it will be garbage collected as soon as the function returns.

The example could hence look like this:

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

def handler(*args, **kwargs):
    print('handled')

def testfn():
    f1 = plt.figure('f1')
    b1 = Button(f1.add_axes([0.4, 0.3, 0.1, 0.04]), 'Click!')
    b1.on_clicked(handler)
    return b1

f2 = plt.figure('f2')
b2 = Button(f2.add_axes([0.4, 0.3, 0.1, 0.04]), 'Click!')
b2.on_clicked(handler)

button = testfn()

plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

Solution verified utilizing a number of different widgets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.