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?

1
  • 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. Commented Oct 13, 2017 at 15:30

1 Answer 1

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.sstatic.net/ySW6o.png')
ICON_PAUSE = plt.imread("https://i.sstatic.net/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()
Sign up to request clarification or add additional context in comments.

1 Comment

That did it. Thanks!

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.