0

I am using matplotlib and tkinter in python 2.7.12. When using a button to run a command that creates a matplotlib figure, saves the figure, then uses plt.close(fig) to close the figure, the tkinter window closes as well (which I don't want). If I remove the plt.close(fig) line, the tkinter window stays open, but then closing the tkinter window does not end the process. How can I properly close the matplotlib figure without closing the tkinter window?

Example code:

import matplotlib.pyplot as plt
import tkinter as tk

def command():

    fig, ax = plt.subplots(1, 1)
    x = range(0, 10, 2)
    y = x
    ax.plot(x, y)
    fig.savefig('test.png')
    plt.close(fig) # this line makes the tkinter window close after the command runs

root = tk.Tk()
button = tk.Button(root, text='click me', command=command)
button.grid(row=0, column=0)
root.mainloop()
Kenny L
  • 1
  • 1
  • Using python 3.6 and matplotlib 2.2.2, this did work as you wanted it to work. Maybe you should try to switch from that archaic python version to a newer one – user8408080 Feb 16 '19 at 01:54
  • Relevant [closing-pyplot-windows](https://stackoverflow.com/questions/11140787/closing-pyplot-windows/11141305#11141305), [how-to-close-a-figure-when-using-tk-backend](https://stackoverflow.com/questions/30037913/how-to-close-a-figure-when-using-tk-backend) – stovfl Feb 16 '19 at 09:55

0 Answers0