qzx
qzx

Reputation: 177

Replacing an existing bar graph with a new one by deleting the old one in Python

I'm new to Python. I was expecting plt.close('all') to remove the old graph when I clicked the button named CHANGE DATA. Instead, the new graph is placed beside the old graph (to its left). Additional clicks would show more graphs, but the old one is never removed.

Am I doing it all wrong or is this a limitation of using tkinter and matplotlib together?

import tkinter as tk
from tkinter import Button
import numpy as np
import matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

matplotlib.use('TkAgg')

def displ_graf(datalst):
    ff = plt.figure(figsize=(5.6,4), dpi=100)
    xx = ff.add_subplot(1,1,1)
    nn = np.arange(len(datalst))
    bb = xx.barh(nn, datalst, 0.8)
    ff.tight_layout
    cc = FigureCanvasTkAgg(ff, master=ww)
    cc.draw()
    cc.get_tk_widget().pack(side=tk.RIGHT)

def graf2():
    plt.close('all')
    data2 = [64, 58, 12, 91, 49, 32, 70, 23, 35]
    displ_graf(data2)

ww = tk.Tk()
ww.geometry('700x400')
ww.state('zoomed')
butt3 = Button(ww,text=' CHANGE DATA ',command=graf2, height=1,width=15)
butt3.place(x=790, y=100)

data1 = [31, 41, 59, 26, 53, 58, 97, 93, 23]
displ_graf(data1)
ww.mainloop()

The image on the left shows the initial screen before clicking the button, and the image on the right shows the screen after clicking on the button:

enter image description here

Upvotes: 2

Views: 831

Answers (1)

Amuoeba
Amuoeba

Reputation: 786

You can do that with the use of cc.get_tk_widget().destroy() . But your code seems kinda clumsily written. So maybe check out this example

Just as an example that it works:

import tkinter as tk
from tkinter import Button
import numpy as np
import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt



def displ_graf(datalst):
    ff = plt.figure(figsize=(5.6,4), dpi=100)
    xx = ff.add_subplot(1,1,1)
    nn = np.arange(len(datalst))
    bb = xx.barh(nn, datalst, 0.8)
    ff.tight_layout
    cc = FigureCanvasTkAgg(ff, master=ww)
    cc.draw()
    cc.get_tk_widget().pack(side=tk.RIGHT)
    return cc

def graf2():    
    data2 = [64, 58, 12, 91, 49, 32, 70, 23, 35]
    displ_graf(data2)

def destroy():
    canv.get_tk_widget().destroy()

ww = tk.Tk()
ww.geometry('700x400')
ww.state('normal')
butt3 = Button(ww,text=' CHANGE DATA ',command=graf2, height=1,width=15)
butt4 = Button(ww,text=' destroy ',command=destroy, height=1,width=15)
butt3.place(x=790, y=100)
butt4.place(x=500, y=100)

data1 = [31, 41, 59, 26, 53, 58, 97, 93, 23]
canv = displ_graf(data1)
ww.mainloop()

But the problem here is that a new instance of cc is created each time you run displ_graph

Upvotes: 2

Related Questions