我的代碼中有一個小問題,因為我有一個帶有復選框的 matplotlib 圖(選擇要繪制的內容),但是當我用 Pyqt5(一個按鈕)打開它時,它確實打開了,但復選框不起作用,我們無法觸摸它們。我的函式運行良好,但不適用于 Pyqt5,我希望我足夠精確,如果不是,我很抱歉。如果可以幫助您,這是我的代碼:
from PyQt5.QtWidgets import QPushButton, QMainWindow, QApplication
import sys
from matplotlib.widgets import CheckButtons
import matplotlib.pyplot as plt
def graph_check () :
x = [1,2,3,4,5,6]
y1 = [1,1,1,1,3,1]
y2 = [0,2,1,2,2,1]
y3 = [4,3,2,0,0,5]
fig,ax = plt.subplots()
p1, = ax.plot(x,y1,color = 'red', label = 'red')
p2, = ax.plot(x,y2,color = 'green', label = 'green')
p3, = ax.plot(x,y3,color = 'blue', label = 'blue')
lines = [p1,p2,p3]
plt.subplots_adjust(left = 0.25, bottom=0.1, right=0.95,top = 0.95)
# checkbuttons widgets
labels = ['red', 'green', 'blue']
activated = [True, True,True]
axCheckbutton = plt.axes([0.03,0.4,0.15,0.15])
chxbox = CheckButtons(axCheckbutton, labels,activated)
def set_visible (label) :
index = labels.index(label)
lines[index].set_visible(not lines[index].get_visible())
plt.draw()
chxbox.on_clicked(set_visible)
plt.show()
# that function does work well, in the end we have a graph with 3 lines and we can make
# them visible or not thanks to the checkbox.
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 600, 400)
self.btn1 = QPushButton('Graph check', self)
self.btn1.setGeometry(130, 215, 125, 55)
self.btn1.clicked.connect(self.btn1_onClicked)
self.show()
def btn1_onClicked(self):
graph_check()
# it works, we can see the graph but it is impossible to use the checkbox...
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
uj5u.com熱心網友回復:
造成這個問題的原因是“chxbox”是一個區域變數,當函式完成執行時,它的參考將被洗掉。一個可能的解決方案是使它成為另一個具有更大范圍的物件的屬性:
# ...
plt.chxbox = CheckButtons(axCheckbutton, labels, activated)
def set_visible(label):
index = labels.index(label)
lines[index].set_visible(not lines[index].get_visible())
plt.draw()
plt.chxbox.on_clicked(set_visible)
# ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394393.html
標籤:Python matplotlib 阴谋 复选框 pyqt5
上一篇:從三列檔案中包含的資料生成3d圖
