Home > OS >  Clearing tkinter canvas content doesn't work
Clearing tkinter canvas content doesn't work

Time:10-24

I have a tkinter canvas where a label and a matplotlib plot are shown. I want to update the content of the canvas and therefore delete what was shown before. To do this I found that canvas.delete('all') is the way to do this. According to the code below the canvas is filled with content and afterwards deleted. But instead of getting an empty window the content is shown. What am I doing wrong?

import tkinter as tk
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# data for plot
x1 = [1, 2, 3]
y1 = [1, 2, 3]

root = tk.Tk()
canvas = tk.Canvas(root, background="grey")
plot_title = tk.Label(canvas, text="plot", font=("Arial 24 bold"), background="grey")

# plot
fig = plt.Figure(figsize=(5, 5))
fig.set_facecolor("grey")
plot1 = fig.add_subplot(111)
plot1.scatter(x1, y1)
chart1 = FigureCanvasTkAgg(fig, canvas)
chart1.get_tk_widget().grid(row=0, column=1)

canvas.grid(row=0, column=0)
plot_title.grid(row=0, column=0, padx=5, pady=5)
canvas.delete('all')

root.mainloop()

CodePudding user response:

when using FigureCanvasTkAgg you have to clear the figure instead of the canvas using fig.clear().

if you want to clear all the data in the canvas then you should destroy it with canvas.destroy() then create another canvas in its place, alternatively if you want to delete the label specifically you can just call plot_title.grid_forget() or plot_title.destroy()

Edit: to keep this information out of comments for future readers, as noted by @acw1668 a label is not a canvas item and so it cannot be removed by .delete("all"), and only items in tk item types in the documentation can be removed by it https://tkdocs.com/tutorial/canvas.html

  • Related