如何从FigureCanvasTkAgg删除NavigationToolbar2Tk?

时间:2020-11-02 14:16:53

标签: tkinter

我使用Tkinter按钮绘制图表。当我单击该按钮时,导航工具栏位于屏幕底部。每次单击按钮时,都会在现有工具栏上放置一个新的导航工具栏。我只想看到一个导航工具栏。 我试图再添加一个按钮并分配一个函数,该函数使用canvas.delete('all')删除现有工具栏。 Clicking more times on Select button results more navigation toolbar.

这是我的代码:

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()

0 个答案:

没有答案