Home > Blockchain >  Removing matplotlib plot figure from tkinter
Removing matplotlib plot figure from tkinter

Time:11-15

I am building a control app, and i use a matplotlib.figure graph to represent some data. I made a function that will do the plotting, but the problem is removing the plot. I can't remove the plot from the window, as it just stays there no matter what. I've tried using tk_widget.place_forget(), tk_widget.destroy(), and figure_subplot.remove(), but the window stays there.

def plot_box_1(sx, sy, px, py):
    fig = Figure(figsize=(sx/100, sy/100), dpi=100)
    pl1 = fig.add_subplot(111)
    pl1.plot(y)
    pltwidget = FigureCanvasTkAgg(fig, master=window)
    pltwidget.draw()
    tkplt = pltwidget.get_tk_widget()
    tkplt.place(x=px, y=py)
    return tkplt, pl1


def b5_updater():
    global tab, asdf, current_after
    p1 = page[5]["p1"]
    p2 = page[5]["p2"]
    box_pos = page[5]["box_pos"]
    if tab == 5:
        if asdf == 100:
            asdf = 0
        p1['value'] = asdf
        p2['value'] = 100 - asdf
        y.append(asdf)
        if len(y) >= plot_lim:
            y.pop(0)
        asdf  = 1
        page[5]["plt_wid"], page[5]["pl1"] = plot_box_1(250, 180, box_pos[2][0]   25, box_pos[2][1]   30)
        current_after = window.after(20, b5_updater)
    else:
        window.after_cancel(current_after) if current_after is not None else None
        p1.destroy()
        p2.destroy()
        page[5]["plt_wid"].place_forget()
        page[5]["pl1"].remove()
        page[5]["plt_wid"].destroy()
        print("Closed B5 Successfully")

Tried .remove, .destroy, .place_forget on multiple items including the Canvas in tkinter, the graph still stayed there.

CodePudding user response:

If you want to completely remove the tkinter widget the following works:

pltwidget.get_tk_widget().destroy()

If you just want to clear the figure, use:

fig.clear()

Both options work for me. You could test it in isolation for yourself by trying these options before the return value of def plot_box_1().

  • Related