I use a Tkinter button to plot my chart. When I click the button, the navigation toolbar is placed on the bottom of the screen. Every time when I click the button, it places a new navigation toolbar over the existing one. I would like to see only one navigation toolbar. I tried to add one more button and assign a function which removes the existing toolbar by using canvas.delete('all'). Clicking more times on Select button results more navigation toolbar.
Here is my code:
import os
import tkinter as tk
from tkinter import ttk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,NavigationToolbar2Tk)
#command function for button1
def plotSelectedFile():
filename = combobox1.get()
txt_file = open(filename,'r')
data = txt_file.readlines()
plotY_values=[]
for i in data:
plotY_values.append(float(i))
txt_file.close()
fig = Figure(figsize = (6, 5), dpi = 100)
plot1 = fig.add_subplot(111)
plot1.plot(plotY_values)
canvas = FigureCanvasTkAgg(fig, master = root)
canvas.draw()
canvas.get_tk_widget().place(x=300,y=100)
toolbar = NavigationToolbar2Tk(canvas, root)
def removeCanvas():
canvas.delete('all')
#list files in current folder (current eg. where this file saved)
#append files to empty list if it is .txt file
arr = os.listdir()
txt_file_list = []
for i in arr:
if i[-3:] == 'txt':
txt_file_list.append(i)
##### INITILIZE TKINTER WINDOW #####
#set window
root=tk.Tk()
root.title('Data plotter program')
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
#set widgets
combobox1 = ttk.Combobox(root,width=15)
combobox1.place(x=40,y=40)
combobox1['values']=txt_file_list
button1 = ttk.Button(root,text='Select',command=plotSelectedFile)
button1.place(x = 200, y = 40)
button2 = ttk.Button(root,text='Remove',command=removeCanvas)
button2.place(x = 300, y = 40)
root.mainloop()