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