【问题标题】:Change matplotlib Button color when pressed按下时更改 matplotlib 按钮颜色
【发布时间】:2013-07-16 10:36:10
【问题描述】:

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

【问题讨论】:

    标签: python user-interface animation button matplotlib


    【解决方案1】:

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

    【讨论】:

    • 谢谢乔!我试试看
    • 在这个例子中只有一个按钮。但是,如果有多个按钮,并且您想更改单击的一个的颜色怎么办?
    • @KurtPeek - 首先,每个按钮都连接到自己的回调,因此当您想要不同的行为时,通常会将不同的回调函数连接到不同的按钮。 (例如,上面的案例使用了闭包,因此可以使用更明确的lambdafunctools.partial 等)。但是,如果需要,您可以将event.inaxesbutton.ax 进行比较。每个Button 实例占用整个Axes,因此发生事件的轴将对应于按钮。但是,如果您有重叠的轴,则有一些警告(例如,另一个轴内的按钮)。
    【解决方案2】:

    在当前的 matplotlib 版本 (1.4.2) 中,'color' 和 'hovercolor' 仅在鼠标 '_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()
    

    【讨论】:

      【解决方案3】:

      如果有人不想在更改颜色时将 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多