同时控制matplotlib中多个按钮的颜色

时间:2017-03-25 16:14:56

标签: python matplotlib interactive

我有三个白色按钮[A,B,C]。当点击这些按钮中的任何一个时,它们应立即变为绿色。当按顺序点击多个按钮时,只有最近点击的按钮应该变为绿色,其他按钮应该返回到原始的白色状态。

我已阅读此页面Change matplotlib Button color when pressed,但它没有帮助。这是我写的代码。此时按钮甚至没有变为绿色。我正在使用Matplotlib 2.0。

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

fig, ax = plt.subplots()


button_axcut={}
button={}

button_axcut['A'] = plt.axes([0.25,0.5, 0.1, 0.1])
button['A'] = Button(button_axcut['A'] ,'A', color='white')

button_axcut['B'] = plt.axes([0.45,0.5, 0.1, 0.1])
button['B'] = Button(button_axcut['B'] ,'B', color='white')

button_axcut['C'] = plt.axes([0.65,0.5, 0.1, 0.1])
button['C'] = Button(button_axcut['C'],'C', color='white')


def A_clicked(event):
    print('A')
    button['A'].ax.set_facecolor('green')
    button['B'].ax.set_facecolor('white')
    button['C'].ax.set_facecolor('white')

    button['A'].ax.figure.canvas.draw()
    button['B'].ax.figure.canvas.draw()
    button['C'].ax.figure.canvas.draw()

def B_clicked(event):
    print('B')
    button['A'].ax.set_facecolor('white')
    button['B'].ax.set_facecolor('green')
    button['C'].ax.set_facecolor('white')

    button['A'].ax.figure.canvas.draw()
    button['B'].ax.figure.canvas.draw()
    button['C'].ax.figure.canvas.draw()

def C_clicked(event):
    print('C')
    button['A'].ax.set_facecolor('white')
    button['B'].ax.set_facecolor('white')
    button['C'].ax.set_facecolor('green')

    button['A'].ax.figure.canvas.draw()
    button['B'].ax.figure.canvas.draw()
    button['C'].ax.figure.canvas.draw()

button['A'].on_clicked(A_clicked)
button['B'].on_clicked(B_clicked)
button['C'].on_clicked(C_clicked)

enter image description here

1 个答案:

答案 0 :(得分:0)

当我将代码作为脚本运行时,最后添加plt.show(),它已经正常工作了。这是使用Qt4Agg以及TkAgg后端在python 2.7中使用matplotlib 2.0进行测试的。

当将鼠标移出轴时,可以稍微压缩代码并确保按钮保持其颜色,如下所示:

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

fig, ax = plt.subplots()


button_axcut={}
button={}

button_axcut['A'] = plt.axes([0.25,0.5, 0.1, 0.1])
button['A'] = Button(button_axcut['A'] ,'A', color='white')

button_axcut['B'] = plt.axes([0.45,0.5, 0.1, 0.1])
button['B'] = Button(button_axcut['B'] ,'B', color='white')

button_axcut['C'] = plt.axes([0.65,0.5, 0.1, 0.1])
button['C'] = Button(button_axcut['C'],'C', color='white')

def click(event):
    for b in ["A", "B", "C"]:
        if button[b].ax == event.inaxes:
            button[b].ax.set_facecolor('green')
            button[b].color = 'green'
        else:
            button[b].ax.set_facecolor('white')
            button[b].color = 'white'
    fig.canvas.draw_idle()


for b in ["A", "B", "C"]:
    button[b].on_clicked(click)

plt.show()