3

I have a matplotlib button widget with an image. After clicking the button, I want to change the image to something else. I tried this:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

FIGURE = plt.figure()
ICON_PLAY = mpimg.imread('./ui/images/play.png')
ICON_PAUSE = mpimg.imread('./ui/images/pause.png')

def play(event):
    print "Starting"
    start_button.image = ICON_PAUSE

start_button = Button(plt.axes([0.1, 0.1, 0.8, 0.8]), '', image=ICON_PLAY)
start_button.on_clicked(play)
plt.show()

The event handler is called, but the image is not changed. Does someone know how to change the image of a matplotlib button widget after construction?

Pete
  • 557
  • 1
  • 4
  • 18
  • Maybe you don't actually need images, but rather use some arrows or so as labels, `Button(ax, label=ur'$\u25B6$')`, as seen in [this answer](https://stackoverflow.com/a/44989063/4124317). – ImportanceOfBeingErnest Oct 13 '17 at 15:30

1 Answers1

5

The image of a matplotlib.widget.Button is an imshow plot in the axes of the button. Hence you may get the existing image from the axes via button_axes.images[0] and set new data on it, button_axes.images[0].set_data(ICON_PAUSE).

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

fig = plt.figure()
ICON_PLAY =  plt.imread('https://i.stack.imgur.com/ySW6o.png')
ICON_PAUSE = plt.imread("https://i.stack.imgur.com/tTa3H.png")

def play(event):
    button_axes.images[0].set_data(ICON_PAUSE)
    fig.canvas.draw_idle()

button_axes = plt.axes([0.3, 0.3, 0.4, 0.4])
start_button = Button(button_axes, '', image=ICON_PLAY)
start_button.on_clicked(play)
plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712