How to clear Tkinter Canvas?
In order to clear a canvas, we can use the delete() method. By specifying “all”, we can delete and clear all the canvas that are present in a tkinter frame.,Tkinter provides a way to add a canvas in a window and when we create a canvas, it wraps up some storage inside the memory. While creating a canvas in tkinter, it will effectively eat some memory which needs to be cleared or deleted.,Now, uncomment the line and execute again to clear the canvas.,The above code will clear the canvas,
Example
#Import the tkinter library from tkinter import * #Create an instance of tkinter frame win = Tk() #Set the geometry win.geometry("650x250") #Creating a canvas myCanvas =Canvas(win, bg="white", height=200, width=200) cordinates= 10, 10, 200, 200 arc = myCanvas.create_arc(cordinates, start=0, extent=320, fill="red") myCanvas.pack() #Clearing the canvas myCanvas.delete('all') win.mainloop()
First, mark the following line as a comment and execute the code.
Answer by Dexter Avery
If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of «all», you could supply the name of a tag. ,Yes, I believe you are creating thousands of objects. If you’re looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.,If you’re creating a game, you probably don’t need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item. ,Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak — eventually your program will crash due to the millions of items that have been drawn.
To clear a canvas, use the delete method. Give it the special parameter «all» to delete all items on the canvas (the string «all» » is a special tag that represents all items on the canvas):
Answer by Evelynn Gray
Given below is the code to achieve this specific functionality:,Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.,The task here is to generate a Python script that can clear Tkinter Canvas. For that delete function of this module will be employed. This method has a special parameter all which represents all the component on the canvas. To clear this canvas give this special parameter to the delete method. Thus, the line below is sufficient to clear the canvas:,Python program to convert a list to string
Answer by Clare Kemp
In this section, we will learn to delete or clear the python Tkinter Canvas.,The delete method is used to clear the canvas or specific object of the canvas.,In this section, we will learn to use matplotlib in python Tkinter canvas,In this tutorial, we will learn to implement an image in Python Tkinter Canvas.
Here is the code with explanation to create python tkinter rectangle using canvas.
from tkinter import * ws = Tk() ws.title('PythonGuides') ws.geometry('300x300') ws.config(bg='#345') canvas = Canvas( ws, height=200, width=200, bg="#fff" ) canvas.pack() canvas.create_rectangle( 30, 30, 180, 120, outline="#fb0", fill="#fb0") ws.mainloop()
from tkinter import * from tkinter import * ws = Tk() ws.title('PythonGuides') ws.geometry('750x400') ws.config(bg='#345') canvas = Canvas( ws, height=500, width=1000, bg="#fff" ) canvas.pack() img = PhotoImage(file="python-tkinter-canvas-image-for-use.png") canvas.create_image(370, 200, image=img) ws.mainloop()
In this code, python tkinter canvas text is displayed.
from tkinter import * ws = Tk() ws.title('PythonGuides') ws.geometry('500x300') ws.config(bg='#345') canvas = Canvas( ws, height=200, width=400, bg="#fff" ) canvas.pack() canvas.create_text( 200,100, fill="darkblue", font="Times 20 italic bold", text="with great power comes \ngreat responsibility") ws.mainloop()
In this code, we have created multiple objects & we have created buttons to delete these objects. rectangles will be deleted when clicked on del_rect button, squares will be deleted when clicked on del_squ button and all the objects will be deleted when click on the del_all button.
from tkinter import * ws = Tk() ws.title('PythonGuides') ws.geometry('500x400') ws.config(bg='grey') canvas = Canvas( ws, height=300, width=400, bg="#fff", ) canvas.pack() canvas.create_rectangle( 30, 20, 200, 100, fill="red", tags="rect", ) canvas.create_oval( 150, 150, 50, 50, fill="blue", tag="circ" ) canvas.create_rectangle( 150, 50, 250, 150, fill="grey", tag="squa" ) canvas.create_text( 180, 250, font= "Times 20", text="Squre,Circle & Rectangle \n inside the canvas", tag='txt' ) btn1 = Button( ws, text='del_rect', font="Times 12", command=lambda:canvas.delete("rect") ) btn1.pack(side=LEFT, fill=X, expand=True) btn2 = Button( ws, text='del_squ', font="Times 12", command=lambda:canvas.delete("squa") ) btn2.pack(side=LEFT, fill=X, expand=True) btn3 = Button( ws, text='del_circ', font="Times 12", command=lambda:canvas.delete("circ") ) btn3.pack(side=LEFT, fill=X, expand=True) btn4 = Button( ws, text='del_all', font="Times 12", command=lambda:canvas.delete("all") ) btn4.pack(side=LEFT, fill=X, expand=True) ws.mainloop()
In this code, We have plotted data using histogram.
from tkinter import * from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import * def click_toplot(): fig = Figure( figsize = (5, 3), dpi = 100 ) #change this data to see difference y = [2, 10, 30, 10, 5, 8, 50, 44, 41] plot1 = fig.add_subplot(111) plot1.hist(y) canvas = FigureCanvasTkAgg( fig, master = ws) canvas.draw() canvas.get_tk_widget().pack() toolbar = NavigationToolbar2Tk( canvas, ws ) toolbar.update() canvas.get_tk_widget().pack() ws = Tk() ws.title('PythonGuides') ws.geometry("650x400") ws.config(bg='#fb0') plot_button = Button(master=ws, command = click_toplot, text = "Click to Plot") plot_button.pack() ws.mainloop()
- Python Tkinter Canvas size can be decided by providing height and width.
- Height is the vertical position of canvas on the parent window.
- Width is the horizontal position of the canvas on the parent window.
- Change in the height & width will change the size of the canvas.
canvas = Canvas( ws, height=200, width=400, bg="#fff" ) canvas.pack()
Answer by Cullen Castillo
# Clear Everything in Tkinter Canvas canvas.delete("all")
Clear canvas in Tkinter without deleting everything
I’m quite new to tkinter (by new i mean I picked it up 2 hours ago) and so there is probably a really simple solution to this I’m just not seeing. But I want to clear a canvas so that I can redraw it. But I don’t want to use delete as I then change the ID# of all the items as I redraw them. Is there a way to clear the canvas that retains the ID# of my items? Thanks I’m programing in Python 2.7 on Ubuntu 11.10.
Better yet, if there was a way to simply redraw the canvas. Clearing it is really just half the way there. I want to redraw the window after moving a frame around and maintain all of me objects IDs.
Why do you think you need to redraw anything? If you «move a frame around» the canvas will redraw itself. Are you seeing a specific behavior that you don’t like?
I want to move a frame, and several ovals that i draw around it and several arcs that i draw between multiple frames.
Ok, So i see now that there is a move function, that lets with things like the ovals and the frames. but only 1 of the points where my arcs attach are changing when I move a frame. (arcs connect the frames) Is there a function to configure canvas items just like you can configure other widgets so that I can change these values as I need?
1 Answer 1
So. It isn’t clearing and redrawing that I want. it is the ability to move and configure items. The functions for which are:
Canvas.configureItem(TAGORID,OPTION=VALUE)
Canvas.move(TAGORID,distanceToMoveX,distanceToMoveY)
thanks for your insight Bryan. That was just the kick in the right direction I needed to figure it out.
To find out what the options are for configItem, call it with only a tag or an ID, it will return the appropriate options. for example, options for an oval are:
- stipple
- disabledoutlinestipple
- activeoutlinestipple
- dash
- disabledwidth
- dashoffset
- activewidth
- fill
- disabledoutline
- offset
- disabledfill
- disableddash
- width
- state
- outlinestipple
- disabledstipple
- activedash
- tags
- activestipple
- activeoutline
- outlineoffset
- activefill
- outline
How can I clear or overwrite a tkinter canvas?
The code below shows one Page of a tkinter GUI I’m currently working on. What I want the ‘Clear Plot Field’-Button to do is what it says: Clear the canvas, because if I plot again the new plot is packed below. OR: How can I overwrite an existing plot, so I can get rid of the button itself?
class PlotPage(tk.Frame): """Page containing the matplotlib graphs""" def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text="PlotPage", font=LARGE_FONT) label.pack(pady=5) button1 = ttk.Button(self, text="Back to Start Page", command=lambda: controller.show_frame(StartPage)) button1.pack(pady=5) buttonPlot = ttk.Button(self, text="Show Plot", command=self.plot) buttonPlot.pack(pady=5) buttonClear = ttk.Button(self, text="Clear Plot Field", command=lambda: controller.show_frame(PlotPage)) buttonClear.pack(pady=5) def plot(self): """generate a simple matplotlib graph for multiple profiles""" f = Figure(figsize=(8,4), dpi=100) a = f.add_subplot(111) for profile in listofProfiles: X_list=profile.indexList Y_list=profile.VL_List [. ] Some lines related to plotting [. ] a.plot(X_list, Y_list, lw=0.3,) canvas = FigureCanvasTkAgg(f, self) canvas.show() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) print("Stuff has been plotted") def clearPlotPage(self): """cleares the whole plot field""" # . print("Plot Page has been cleared")
3 Answers 3
Simply Googling «clear tkinter canvas» got me this, this, this and this.
Short answer: calling canvas.delete(‘all’) will clear the entire canvas.
I found and tried this as well, but the problem is: The canvas does not exist within the clear-method. So how can I get around this?
@Tybald you can make canvas a class attribute by adding self. as a prefix. This will allow your clearPlotPage(self) method the ability to work with self.canvas and you can delete it from there and then call self.plot() again to recreate.
@Mike-SMT if you delete the canvas you need to redo any formatting or attribute setting again (assuming you’ve saved that info somewhere). It also might mess with your layout depending on which manager you’re using
@en_Knight it wont mess with the layout if you use a frame to hold the canvas. If you create the canvas in the first place within a function then its just a matter of deleted the canvas and rerunning that function to created it. My app does it this way with no issues.
I would destroy() the canvas and then rerun plot() . To do this you need to make canvas a class attribute like this self.canvas . Now that we have a class attribute any of your methods can work with self.canvas without issue.
Take a look at this code I modified from your question and let me know if you have any questions.
class PlotPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.canvas = None label = ttk.Label(self, text="PlotPage", font=LARGE_FONT) label.pack(pady=5) button1 = ttk.Button(self, text="Back to Start Page", command=lambda: controller.show_frame(StartPage)) button1.pack(pady=5) buttonPlot = ttk.Button(self, text="Show Plot", command=self.plot) buttonPlot.pack(pady=5) buttonClear = ttk.Button(self, text="Clear Plot Field", command=lambda: controller.show_frame(PlotPage)) buttonClear.pack(pady=5) def plot(self): if self.canvas == None: f = Figure(figsize=(8,4), dpi=100) a = f.add_subplot(111) for profile in listofProfiles: X_list=profile.indexList Y_list=profile.VL_List # [. ] Some lines related to plotting [. ] a.plot(X_list, Y_list, lw=0.3,) self.canvas = FigureCanvasTkAgg(f, self) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(self.canvas, self) toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) print("Stuff has been plotted") else: print("Plot already plotted please clear first") def clearPlotPage(self): self.canvas.destroy() self.canvas = None self.plot() print("Plot Page has been cleared")