I'm running an animation using matplotlib's FuncAnimation
to display data (live) from a microprocessor. I'm using buttons to send commands to the processor and would like the color of the button to change after being clicked, but I can't find anything in the matplotlib.widgets.button
documentation (yet) that achieves this.
class Command:
def motor(self, event):
SERIAL['Serial'].write(' ')
plt.draw()
write = Command()
bmotor = Button(axmotor, 'Motor', color = '0.85', hovercolor = 'g')
bmotor.on_clicked(write.motor) #Change Button Color Here
Just set button.color
.
E.g.
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import itertools
fig, ax = plt.subplots()
button = Button(ax, 'Click me!')
colors = itertools.cycle(['red', 'green', 'blue'])
def change_color(event):
button.color = next(colors)
# If you want the button's color to change as soon as it's clicked, you'll
# need to set the hovercolor, as well, as the mouse is still over it
button.hovercolor = button.color
fig.canvas.draw()
button.on_clicked(change_color)
plt.show()
In current matplotlib version (1.4.2) 'color' and 'hovercolor' are took into account only when mouse '_motion' event has happened, so the button change color not when you press mouse button, but only when you move mouse afterwards.
Nevertheless, you can change button background manually:
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import itertools
button = Button(plt.axes([0.45, 0.45, 0.2, 0.08]), 'Blink!')
def button_click(event):
button.ax.set_axis_bgcolor('teal')
button.ax.figure.canvas.draw()
# Also you can add timeout to restore previous background:
plt.pause(0.2)
button.ax.set_axis_bgcolor(button.color)
button.ax.figure.canvas.draw()
button.on_clicked(button_click)
plt.show()