关闭/解压缩对象" matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"

时间:2015-09-30 21:05:33

标签: python matplotlib

这是采用图形并在Tkinter窗口上显示它的代码。如何解压缩/删除#34; canvas"从GUI?

    from Tkinter import *
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

    def plot(x, y):
        fig = plt.figure()
        ax1 = fig.add_subplot(1,1,1)
        ax1.plot(x,y)
        return fig

    plt = plot(1,1)
    root = Tk()
    canvas = FigureCanvasTkAgg(plt, master=root)
    canvas.get_tk_widget().pack() 

1 个答案:

答案 0 :(得分:0)

如果您要删除图表并释放父框架/窗口,请致电canvas.get_tk_widget().destroy()

例如:

import Tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

def main():
    fig = plot(range(10), range(10))
    root = tk.Tk()
    canvas = FigureCanvasTkAgg(fig, master=root)
    canvas.get_tk_widget().pack()

    root.bind_all('<Button-1>', lambda event: remove_plot(canvas))

    root.mainloop()

def plot(x, y):
    fig = Figure()
    ax1 = fig.add_subplot(1,1,1)
    ax1.plot(x,y)
    return fig

def remove_plot(canvas):
    canvas.get_tk_widget().destroy()

main()

这只会摧毁这个人物的tk小部件。该数字仍然存在,可以再次添加,假设它没有超出范围并被垃圾收集。 (此外,该图将像任何其他对象一样被垃圾收集,因为我们没有使用pyplot状态机。)