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()