PyQt4 / matplotlib - 如何释放内存?

时间:2013-10-05 17:29:06

标签: python matplotlib pyqt4

我正在使用matplotlib Qt4后端绘制大量数据。

我的问题是:你如何正确关闭matplotlib图并释放图中占用的内存? figure.close()不执行任务,也没有关闭绘图窗口。

下面的最小工作示例显示了问题:

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt
from numpy.random import random

class MainWindow(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setGeometry(50, 50, 200, 200)

        self.bPlot = QtGui.QPushButton('Plot',self)
        self.bPlot.resize(75,25)
        self.bPlot.move(25, 25)
        self.bPlot.clicked.connect(self.bPlotHandler)

        self.bClosePlot = QtGui.QPushButton('Close plot',self)
        self.bClosePlot.resize(75,25)
        self.bClosePlot.move(25, 75)
        self.bClosePlot.clicked.connect(self.bClosePlotHandler)

        self.show()

    def bPlotHandler(self):
        self.plotApp=PlotWindow()
        self.plotApp.plot()
        self.plotApp.show()

    def bClosePlotHandler(self):
        self.plotApp.figure.clf()
        self.plotApp=None

class PlotWindow(QtGui.QDialog):
    def __init__(self, parent=None):
        super(PlotWindow, self).__init__(parent)

        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        self.setLayout(layout)

    def plot(self):
        data=random(1e5)
        ax = self.figure.add_subplot(111)
        ax.plot(data)
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = MainWindow()
    main.show()

    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

也许你可以删除变量?像

这样的东西
del self.figure
self.figure = None