按下时更改matplotlib按钮颜色

时间:2013-07-17 18:12:41

标签: python user-interface animation button matplotlib

我正在使用matplotlib的FuncAnimation运行动画,以便从微处理器显示数据(实时)。我正在使用按钮向处理器发送命令,并希望点击后按钮的颜色会发生变化,但我在matplotlib.widgets.button文档中找不到任何可以实现此目的的内容。

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

2 个答案:

答案 0 :(得分:4)

只需设置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()

答案 1 :(得分:1)

在当前的matplotlib版本(1.4.2)中,只有当鼠标“_motion”事件发生时才会考虑“颜色”和“hovercolor”,因此当您按下鼠标按钮时按钮不会改变颜色,但仅在您移动时小鼠之后。

然而,您可以手动更改按钮背景:

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