检查Matplotlib中是否单击了按钮

v8wbuo2f  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(94)

我试图在Matplotlib中使用检查按钮,并确定是否单击了检查按钮。因此,我希望:在我的代码中单击按钮3后,如果按钮1被选中,它将打印'1',如果按钮2被选中,它将打印'2'。但是我的代码不是这样工作的,它只能打印'3'。请查看它并指出我的错误。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
from matplotlib.widgets import Button, RadioButtons, CheckButtons

fig = plt.figure()
ax = fig.add_subplot(projection='3d')
p1 = ax.scatter(5,6,7)
p2 = ax.scatter(1,2,3, color='red', marker='+', s=1e2)
p3 = ax.scatter(4,5,6, color='blue', marker='+', s=1e2)

lines_1 = [p1, p2]
labels_1 = ["Button_1"]

def func1(label):
        index1 = labels_1.index(label)
        lines_1[index1].set_visible(not lines_1[index1].get_visible())
        lines_1[index1+1].set_visible(not lines_1[index1+1].get_visible())
        fig.canvas.draw()

a = [True]

lines_2 = [p3]
labels_2 = ["Button_2"]

def func2(label):
        index2 = labels_2.index(label)
        lines_2[index2].set_visible(not lines_2[index2].get_visible())
        fig.canvas.draw()

b = [True]

# xposition, yposition, width, height
ax_check1 = plt.axes([0, 0.01, 0.2, 0.15])
ax_check2 = plt.axes([0, 0.16, 0.2, 0.15])
plot_button1 = CheckButtons(ax_check1, labels_1, a)
plot_button2 = CheckButtons(ax_check2, labels_2, b)

plot_button1.on_clicked(func1)
plot_button2.on_clicked(func2)

def func3(label):
        if labels_1 == 'On' and labels_2 == 'Off':
                print('1')
        elif labels_1 == 'Off' and labels_2 == 'On':
                print('2')
        else:
                print('3')

axButn1 = plt.axes([0, 0.31, 0.15, 0.08])
btn1 = Button(axButn1, label="Button 3", color='pink')
btn1.on_clicked(func3)

plt.show()
1rhkuytd

1rhkuytd1#

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
from matplotlib.widgets import Button, RadioButtons, CheckButtons

fig = plt.figure()
ax = fig.add_subplot(projection='3d')
p1 = ax.scatter(5,6,7)
p2 = ax.scatter(1,2,3, color='red', marker='+', s=1e2)
p3 = ax.scatter(4,5,6, color='blue', marker='+', s=1e2)

lines_1 = [p1, p2]
labels_1 = ["Button_1"]

def func1(label):
        index1 = labels_1.index(label)
        lines_1[index1].set_visible(not lines_1[index1].get_visible())
        lines_1[index1+1].set_visible(not lines_1[index1+1].get_visible())
        print(1)
        fig.canvas.draw()

a = [True]

lines_2 = [p3]
labels_2 = ["Button_2"]

def func2(label):
        index2 = labels_2.index(label)
        lines_2[index2].set_visible(not lines_2[index2].get_visible())
        print(2)
        fig.canvas.draw()

b = [True]

# xposition, yposition, width, height
ax_check1 = plt.axes([0, 0.01, 0.2, 0.15])
ax_check2 = plt.axes([0, 0.16, 0.2, 0.15])
plot_button1 = CheckButtons(ax_check1, labels_1, a)
plot_button2 = CheckButtons(ax_check2, labels_2, b)

plot_button1.on_clicked(func1)
plot_button2.on_clicked(func2)

plt.show()

我希望这能如你所愿

相关问题