Python Matplotlib';函数的作用是:关闭Tkinter GUI窗口

Python Matplotlib';函数的作用是:关闭Tkinter GUI窗口,python,matplotlib,tkinter,Python,Matplotlib,Tkinter,我正在尝试使用Tkinter制作一个简单的GUI,它使用Matplotlib生成大量绘图并将它们保存到硬盘上 附加的是一个简单的代码,可以实现这一点,但是在保存所有绘图后,Tkinter GUI关闭,脚本停止。我认为这个问题可能与plt.close()有关,因为当我删除plt.close()时,GUI窗口不再关闭,但毫不奇怪,内存很快就会被填满,直到整个事件崩溃 我尝试使用plt.clf(),plt.gcf().clear(),fig.clear(),而不是plt.close(),但都不起作用。

我正在尝试使用Tkinter制作一个简单的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、windows7、tkinter8.6和matplotlib3.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()

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

import matplotlib
matplotlib.use("Agg")

在顶部(导入pyplot之前)将消除该问题。此外,您还可以删除
root.destroy()
,因为这似乎不是必需的,否则可能会导致错误

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

import matplotlib
matplotlib.use("Agg")

在顶部(导入pyplot之前)将消除该问题。此外,您还可以删除
root.destroy()
,因为这似乎不是必需的,否则可能会导致错误

我无法复制这个。当我运行代码时,tk窗口保持打开状态,直到我按下X按钮。相关@ImportanceOfBeingErnest您可以与我共享Matplotlib、Tkinter和Python的版本以及操作系统吗?我无法复制。当我运行代码时,tk窗口一直打开,直到我按下X按钮。相关@ImportanceOfBeingErnest您能与我分享Matplotlib、Tkinter和Python的版本以及操作系统吗?