2

我正在使用 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
4

3 回答 3

5

刚设置button.color

例如

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()
于 2013-07-17T20:58:56.360 回答
2

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

不过,您可以手动更改按钮背景:

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()
于 2015-01-22T00:06:07.037 回答
0

如果有人不想在更改颜色时将 Button 作为全局变量,这里有一个解决方案:

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()
于 2021-11-26T17:39:23.013 回答