Daniel
Daniel

Reputation: 173

how to update the plot in my tkinter window?

I am trying my hand at creating a GUI. I have already written the following code. However, I would like the plotted image not just to be added, but the existing image to be "updated". Where is my error in the code?

I tried to use the pack_forget() method but this doesnt work for me.

I am grateful for any help.

Thanks

from tkinter import * 
from matplotlib.figure import Figure 
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,  
NavigationToolbar2Tk) 
import pandas as pd
import matplotlib as plt
from sklearn.cluster import KMeans

  
def plot_Raw_Data(): 

    fig = Figure(figsize = (5, 5), 
                 dpi = 100
                 ) 
  
    
    ## Benennung CSV File Name
    csv_file_1 = 'Mappe1.csv'

    ## Erstelle DF aus CSV Datei. -> Sep müssen wir anpassen, da sonst eventuell ein Fehler mit den richtigen Daten auftritt
    df = pd.read_csv(csv_file_1, sep = ';')

    ## gebe die ersten Zeilen des DF aus, zur Fehlerüberprüfung, kann später auskommentiert werden
    print(df.head())

 
    plot1 = fig.add_subplot(111) 
  
    
    plot1.scatter(df['Temperature'], df['Pressure']) 
  
    
    
    canvas = FigureCanvasTkAgg(fig, 
                               master = window)   
    canvas.draw() 
  
    
    canvas.get_tk_widget().pack() 
  
    
    toolbar = NavigationToolbar2Tk(canvas, 
                                   window) 
    toolbar.update() 
  
    
    canvas.get_tk_widget().pack() 


window = Tk() 
  
window.title('GSWN') 
  
window.geometry("500x500") 
  
plot1_button = Button(master = window,  
                     command = plot_Raw_Data,
                     height = 2,  
                     text = "Plot Raw Data"
                     
                     ) 
  
plot1_button.pack() 


window.mainloop() 

This is the GUI:

enter image description here

Upvotes: 0

Views: 189

Answers (1)

mespinosa
mespinosa

Reputation: 5

It looks like you are creating a new Figure every time you want to update the canvas.

fig = Figure(figsize = (5, 5), dpi = 100)

Maybe you should only create once the fig outside the function and pass it as an argument.

Upvotes: 1

Related Questions