Skip to content Skip to sidebar Skip to footer

Change Matplotlib Button Color When Pressed

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

Solution 1:

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'])

defchange_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()

Solution 2:

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!')


defbutton_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()

Solution 3:

In case anyone do not want to make the Button as a global variable when changing the colour, here is a solution:

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

def change_color(button):
    button.color = 'red'

def main():
    button = Button(plt.axes([0.5, 0.5, 0.25, 0.05]), 'Click here')
    button.on_clicked(lambda _: change_color(button))
    plt.show()

if __name__ == "__main__":
    main()

Post a Comment for "Change Matplotlib Button Color When Pressed"