FigureCanvasTkAgg的声明导致内存泄漏

时间:2015-06-08 12:48:37

标签: python python-2.7 matplotlib memory-leaks tkinter

我很难搞清楚为什么ImageCanvasTkAgg的声明导致内存泄漏,我在我的类 # pndwinBottom is a paned window of the main screen self.__drawplotFrame = Frame(pndwinBottom, width=WIDTH, height=HEIGHT) # the frame on which we will add our canvas for drawing etc. self.__fig = plt.figure(figsize=(16,11)) self.__drawplotCanvas = FigureCanvasTkAgg(self.__fig, master=self.__drawplotFrame) 方法中有以下几行:

self.__fig = plt.figure(figsize=(16, 11))

问题是在运行我的应用程序并退出时,python32.exe仍然在我的进程窗口中并且会阻塞我的计算机。然而,注释掉这三行将允许我的应用程序退出并且该过程将正确终止。这些行可以对我的应用程序做些什么,以防止在应用程序完成后进程结束?感谢

修改

内存泄漏似乎只是由行@ShowQuotingTool引起的。在退出之前,我是否需要用plt进行某种解构?

2 个答案:

答案 0 :(得分:1)

我猜这是因为当Tkinter窗口关闭时,pyplot数字没有被破坏。
与使用Figure的{​​{3}}尝试一样:

from matplotlib.figure import Figure

self.__fig = Figure(figsize=(16,11))

使用示例:

import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')

from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

class App():
    def __init__(self, parent):

        self.__drawplotFrame = tk.Frame(parent, width=500, height=500)
        self.__drawplotFrame.pack()

        self.__fig = Figure(figsize=(16,11))
        self.__p = self.__fig.add_subplot(1,1,1)
        self.__p.plot(range(10), range(10))

        self.__drawplotCanvas = FigureCanvasTkAgg(self.__fig, master=self.__drawplotFrame)
        self.__drawplotCanvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

root = tk.Tk()
App(root)
root.mainloop()

答案 1 :(得分:1)

我遇到内存泄漏问题,我想我找到了解决方案。在我的__init__方法中,我创建了一个框架,然后将其传递给绘图函数来完成实际工作。在该函数中,我将创建一个新的matplotlib.figure.Figure实例,由于某种原因,当函数超出范围时,它不会被销毁。

为了解决这个问题,我做到了这一点:在__init__方法中,我不仅创建了框架,还创建了图形(带有轴)和画布:

;

然后,在绘图方法中,

5        6357   G      V       ACT/wo%%$2.25;56842;ALT;Raw_score=1.358;Actual_score=10.685

就这样,泄漏消失了!