Matplotlib的close()函数导致Tkinter GUI窗口关闭

时间:2019-02-07 13:16:55

标签: python matplotlib tkinter

我正在尝试使用Tkinter制作一个简单的GUI,该GUI使用Matplotlib生成大量图并将其保存到硬盘中。

已附加是执行此操作的简单代码,但是,在保存所有绘图后,Tkinter GUI关闭并且脚本停止。我认为这个问题可能与plt.close()有关,因为当我删除 plt.close()时,GUI窗口不再关闭,但这并不奇怪,内存很快就被填满了直到整个崩溃。

我尝试使用 plt.clf() plt.gcf()。clear() fig.clear代替plt.close() (),但没有一个起作用。它们使GUI窗口保持不变,但是会导致内存问题。

有人知道为什么plt.close()关闭Tkinter GUI窗口,以及如何防止它发生吗?完成后,我需要GUI停留并确定要从内存中删除的对象和他们在一起。

我正在使用Python3.6.3rc1,Windows 7,Tkinter 8.6和Matplotlib 3.0.2。

from tkinter import *
import matplotlib.pyplot as plt
import os

def make_plot():
    x = [1, 2, 3, 4, 5]
    y = [1, 2, 3, 4, 5]
    for j in range(0,20):
            fig = plt.figure(num=None, figsize=(20, 10), dpi=200, facecolor='w', edgecolor='w')
            plt.plot(x,y)
            plt.xlabel("x")
            plt.ylabel("y")
            out_name = os.getcwd()+ "\\" +  str(j)+".png"
            print(out_name)
            plt.savefig(out_name)
            plt.close()

class Application(Frame):
    def run_make_plot(self):
        make_plot()

    def createWidgets(self):
        self.button = Button(self)
        self.button["text"] = "Plot"
        self.button["command"] = self.run_make_plot
        self.button.pack()

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

1 个答案:

答案 0 :(得分:0)

这取决于后端。当然,在使用tkinter时,您想使用tkagg后端,但这就是问题的原因。但是,在这种情况下,您不需要任何交互式后端,因此添加

import matplotlib
matplotlib.use("Agg")

在顶部(在导入pyplot之前)将解决该问题。另外,您可以删除root.destroy(),因为这似乎没有必要,否则可能会导致错误。

相关问题