【问题标题】:Matplotlib's close() function causes the Tkinter GUI window to closeMatplotlib 的 close() 函数导致 Tkinter GUI 窗口关闭
【发布时间】: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


【解决方案1】:

这取决于后端。当然,您想在使用 tkinter 时使用 tkagg 后端,但这就是问题的原因。但是,在这种情况下,您不需要任何交互式后端,因此添加

import matplotlib
matplotlib.use("Agg")

在顶部(在导入 pyplot 之前)会解决这个问题。此外,您可以删除root.destroy(),因为这似乎没有必要,否则可能会导致错误。

【讨论】:

    猜你喜欢
    • 2013-12-22
    • 2016-11-27
    • 2014-09-26
    • 1970-01-01
    • 2013-07-23
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多