我有一个带有图像的matplotlib按钮小部件。单击按钮后,我想将图像更改为其他内容。我试过这个:
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()
调用事件处理程序,但图像不会更改。有人知道如何在构建后更改matplotlib按钮小部件的图像吗?
答案 0 :(得分:2)
matplotlib.widget.Button
的图像是按钮轴上的imshow
图。因此,您可以通过button_axes.images[0]
从轴获取现有图像,并在其上设置新数据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()