首页 > 解决方案 > 关闭 matplotlib 图而不关闭 tkinter

问题描述

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

标签: pythontkinter

解决方案


推荐阅读