Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tkinter -- How to clear FigureCanvasTkAgg object if exists or similar?

Trying to create a tkinter based window that allows user to create a chart on button click, refreshing the chart -- not adding another, each time. All without creating a new window. The idea is click -> create chart, click again -> replace the chart with new chart in same spot. No extra clicks, no extra button to close. Using matplotlib.backends.backend_tkagg and FigureCanvasTkAgg. Documentation appears to be virtually non-existent on this. Tried various attributes in .get_tk_widget() to see if I could test if it exists already, get a list, etc. Also tried clearing canvas.

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *

class testme:
    def __init__(self,frame1):
        self.frame1=frame1     
        self.button=Button(self.frame1,text="DRAWME",command=self.plot) 
        self.button1=Button(self.frame1,text="CLEARME",command=self.clearme)
        self.button.pack()       
        self.button1.pack()      

    def plot(self):                   
        f=Figure(figsize=(5,1)) 
        aplt=f.add_subplot(111)       
        aplt.plot([1,2,3,4]) 
        self.wierdobject = FigureCanvasTkAgg(f, master=self.frame1) 
        self.wierdobject.get_tk_widget().pack() 
        self.wierdobject.draw()                

    def clearme(self):       
       self.wierdobject.get_tk_widget().pack_forget()     

root=Tk()
aframe=Frame(root)
testme(aframe)
aframe.pack()  #packs a frame which given testme packs frame 1 in testme
root.mainloop()

Attached example code almost approximates my goal but it requires a "CLEARME" button (which only works right if "DRAWME" was only clicked once. I just want some kind of if statement that checks if there is a FigureCanvasTkAgg object in the frame already and if so remove it instead of a button click.

After a number of attempts I concluded I have a fundamental misunderstanding of more than one thing that's going on here.

like image 764
Blaine Kelley Avatar asked May 15 '19 16:05

Blaine Kelley


1 Answers

For your current setup, just add a try clause at the start of your plot function.

def plot(self):   
    try: 
        self.wierdobject.get_tk_widget().pack_forget()
    except AttributeError: 
        pass                
    f=Figure(figsize=(5,1)) 
    aplt=f.add_subplot(111)       
    aplt.plot([1,2,3,4]) 
    self.wierdobject = FigureCanvasTkAgg(f, master=self.frame1) 
    self.wierdobject.get_tk_widget().pack() 
    self.wierdobject.draw()    
like image 174
Henry Yik Avatar answered Sep 30 '22 05:09

Henry Yik