Close/Unpack Object “matplotlib.backends.backend_tkagg.FigureCanvasTkAgg”

前端 未结 1 991
执念已碎
执念已碎 2021-01-23 12:12

This is code that takes a figure and displays it on a Tkinter window. How do I unpack/delete \"canvas\" from the GUI?

    from Tkinter import *
    import numpy          


        
1条回答
  •  野的像风
    2021-01-23 12:48

    If you'd like to remove the plot and free up the parent frame/window, call 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('', 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. 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.)

    0 讨论(0)
提交回复
热议问题