2

When I put plt.show() in a different method, it's impossible to click the button :

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

class ButtonTest:
    def __init__(self):
        ax = plt.axes([0.81, 0.05, 0.1, 0.075])
        bnext = Button(ax, 'Next')
        bnext.on_clicked(self._next)
#         plt.show()

    def show(self):
        print("when i put plt.show() in a different method, it's impossible to click the button")
        plt.show()

    def _next(self, event):
        print("next !")

b = ButtonTest()
b.show()

The button is not even highlighted when the mouse moves over it. Would someone know why and how to solve the problem ?

Luc PHAN
  • 316
  • 2
  • 13

1 Answers1

1

What's happening is that the button object is being garbage collected before the plot is displayed. You'll need to keep a reference to it around.

For example, if you change

bnext = Button(...)

to

self.bnext = Button(...)

Everything should work.

As a complete example:

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

class ButtonTest:
    def __init__(self):
        ax = plt.axes([0.81, 0.05, 0.1, 0.075])
        self.bnext = Button(ax, 'Next')
        self.bnext.on_clicked(self._next)

    def show(self):
        plt.show()

    def _next(self, event):
        print("next !")

ButtonTest().show()
Joe Kington
  • 275,208
  • 71
  • 604
  • 463