我在python 2.7.12中使用matplotlib和tkinter。使用按钮运行创建matplotlib图形的命令时,保存图形,然后使用plt.close(fig)
关闭图形,tkinter窗口也将关闭(我不希望如此)。如果删除plt.close(fig)
行,则tkinter窗口保持打开状态,但是关闭tkinter窗口不会结束该过程。如何在不关闭tkinter窗口的情况下正确关闭matplotlib图形?
示例代码:
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()