1

I'm trying to make a simple GUI using Tkinter that uses Matplotlib to generate a large number of plots and saves them to hard drive.

Attached is a simple code that does this, however after all plots are saved, the Tkinter GUI closes and the script stops. I think this problem might have to do with plt.close(), because When I remove plt.close(), the GUI window does not close anymore, but not surprisingly, the memory gets filled up quickly until the whole thing crashes.

Instead of plt.close(), I tried using plt.clf(), plt.gcf().clear(), fig.clear() and none of them worked. They make the GUI window to stay, but they cause the memory issue.

Does anybody know why plt.close() closes the Tkinter GUI window and how can one prevent it? I need the GUI to stay and figure objects to get removed from memory when I'm done with them.

I'm using Python3.6.3rc1, Windows 7, Tkinter 8.6, and 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()
SMR
  • 11
  • 3
  • I cannot reproduce this. When I run the code, the tk window stays open until I press the X button. – ImportanceOfBeingErnest Feb 07 '19 at 13:28
  • Relevant [closing-pyplot-windows](https://stackoverflow.com/questions/11140787/closing-pyplot-windows) – stovfl Feb 07 '19 at 13:32
  • @ImportanceOfBeingErnest Can you please share with me the version of your Matplotlib, Tkinter and Python as well as the operating system? – SMR Feb 08 '19 at 10:36

1 Answers1

1

It's depending on the backend. Of course you want to use the tkagg backend when working with tkinter, but that is the cause of the issue. In this case however, you do not need any interactive backend, so adding

import matplotlib
matplotlib.use("Agg")

on top (before importing pyplot) would get rid of the issue. Also, you can remove root.destroy(), because that does not seem necessary and might cause an error otherwise.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712