Reputation: 567
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?
Upvotes: 3
Views: 2653
Reputation: 339250
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()
Upvotes: 5