【发布时间】:2019-02-07 13:16:54
【问题描述】:
我正在尝试使用 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、Windows 7、Tkinter 8.6 和 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()
【问题讨论】:
-
我无法重现这个。当我运行代码时,tk 窗口会一直打开,直到我按下 X 按钮。
-
@ImportanceOfBeingErnest 能否分享一下您的 Matplotlib、Tkinter 和 Python 版本以及操作系统?
标签: python matplotlib tkinter