简体   繁体   English

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

[英]Close/Unpack Object “matplotlib.backends.backend_tkagg.FigureCanvasTkAgg”

This is code that takes a figure and displays it on a Tkinter window. 这是获取图形并将其显示在Tkinter窗口上的代码。 How do I unpack/delete "canvas" from the GUI? 如何从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() 

If you'd like to remove the plot and free up the parent frame/window, call canvas.get_tk_widget().destroy() . 如果要删除图并释放父框架/窗口,请调用canvas.get_tk_widget().destroy()

For example: 例如:

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

This only destroys the figure's tk widget. 这只会破坏图形的tk小部件。 The figure still exists and could be added again, assuming it hasn't gone out of scope and been garbage collected. 该图仍然存在,并且可以假定它没有超出范围并已被垃圾回收,可以再次添加。 (Also, the figure will be garbage collected just like any other object as we're not using the pyplot state machine.) (此外,由于我们不使用pyplot状态机,因此该图将像其他任何对象一样被垃圾收集。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM