How to clear Tkinter Canvas?

TkinterPythonServer Side ProgrammingProgramming

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.

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.

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

The above code will clear the canvas,

Output

First, mark the following line as a comment and execute the code.

myCanvas.delete('all')

It will produce the following window: 

Now, uncomment the line and execute again to clear the canvas.

raja
Published on 26-Mar-2021 11:05:13
Advertisements