PyQt5:运行时错误:类型为FigureCanvasQTAgg的包装C/C++对象已被删除。

5
我最近几天一直在查看stackoverflow的帖子,以解决我遇到的问题,尝试了几种方法后,我仍然无法使我的代码工作。 我正在尝试创建一个简单的GUI,在按下按钮时可以显示一个图形。 当我运行主模块时,程序会启动。 但是当我点击我的“plot”按钮时,我会收到以下错误:

RuntimeError: wrapped C/C++ object of type FigureCanvasQTAgg has been deleted

现在我读到这与删除C ++对象有关,而python包装器仍然存在,但我似乎无法解决此问题。 我最关心的是尽可能保持GUI的模块化,因为我想扩展下面显示的示例代码。 有人有解决我的问题的好方法吗?

main.py

import sys
from PyQt5.QtWidgets import *

from GUI import ui_main

app = QApplication(sys.argv)
ui = ui_main.Ui_MainWindow()
ui.show()
sys.exit(app.exec_())

ui_main.py

from PyQt5.QtWidgets import *

from GUI import frame as fr

class Ui_MainWindow(QMainWindow):

    def __init__(self):
        super(Ui_MainWindow, self).__init__()

        self.central_widget = Ui_CentralWidget()
        self.setCentralWidget(self.central_widget)

        self.initUI()

    def initUI(self):

        self.setGeometry(400,300,1280,600)
        self.setWindowTitle('Test GUI')

class Ui_CentralWidget(QWidget):

    def __init__(self):
        super(Ui_CentralWidget, self).__init__()

        self.gridLayout = QGridLayout(self)

        '''Plot button'''
        self.plotButton = QPushButton('Plot')
        self.plotButton.setToolTip('Click to create a plot')
        self.gridLayout.addWidget(self.plotButton, 1, 0)

        '''plotFrame'''
        self.plotFrame = fr.PlotFrame()
        self.gridLayout.addWidget(self.plotFrame,0,0)

        '''Connect button'''
        self.plotButton.clicked.connect(fr.example_figure)

frame.py

from PyQt5.QtWidgets import *

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt

class PlotFrame(QFrame):

    def __init__(self):
        super(PlotFrame, self).__init__()

        self.gridLayout = QGridLayout(self)

        self.setFrameShape(QFrame.Box)
        self.setFrameShadow(QFrame.Raised)
        self.setLineWidth(3)

        self.figure = plt.figure(figsize=(5, 5))
        self.canvas = FigureCanvas(self.figure)
        self.gridLayout.addWidget(self.canvas,1,1)

def example_figure():

    plt.cla()
    ax = PlotFrame().figure.add_subplot(111)
    x = [i for i in range(100)]
    y = [i ** 0.5 for i in x]
    ax.plot(x, y, 'r.-')
    ax.set_title('Square root plot')
    PlotFrame().canvas.draw()
1个回答

2
每次使用PlotFrame()都会创建一个新的对象,在你的例子中,你在example_figure中创建了两个对象,但它们是局部的,因此当该函数执行时,它们将自动删除,导致你指出的错误,因为引用丢失。当在不通知matplotlib的情况下移除对象时,一种解决方法是将对象传递给函数。 ui_main.py
# ...

class Ui_CentralWidget(QWidget):
    # ...
        '''Connect button'''
        self.plotButton.clicked.connect(self.on_clicked)

    def on_clicked(self):
        fr.example_figure(self.plotFrame)

frame.py

# ...

def example_figure(plot_frame):
    plt.cla()
    ax = plot_frame.figure.add_subplot(111)
    x = [i for i in range(100)]
    y = [i ** 0.5 for i in x]
    ax.plot(x, y, 'r.-')
    ax.set_title('Square root plot')
    plot_frame.canvas.draw()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接