Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Python
  3. Question
Python

How to clear Tkinter Canvas using Python?

Asked by Augustina Fuentes Apr 19, 2021 12.5K views 2 answers
Share

About this question

 When I draw a shape using the following piece of code:

canvas.create_rectangle(10, 10, 50, 50, color="green")

Does Tkinter keep track of the fact that it was created?

In a simple game, I'm making my code which has one Frame create a bunch of rectangles, and then I draw a big black rectangle to clear the screen, and then draw another set of updated rectangles, and so on.

Am I creating thousands of rectangle objects in memory?

I know you can assign the code above to a variable, but if I don't do that and just draw directly to the canvas, does it stay in memory, or does it just draw the pixels, like in the HTML5 canvas?

Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Apr 24, 2024

To clear a Tkinter canvas in Python, you can use the delete() method of the canvas widget. This method allows you to remove all items drawn on the canvas, effectively clearing it. Here's how you can do it:

import tkinter as tk
def clear_canvas():
    canvas.delete("all")
# Create a Tkinter window
root = tk.Tk()
root.title("Clear Canvas Example")
# Create a canvas
canvas = tk.Canvas(root, width=400, height=300, bg="white")
canvas.pack()
# Create some items on the canvas (for demonstration)
# Example: Draw a rectangle
canvas.create_rectangle(50, 50, 200, 150, fill="blue")
# Create a button to clear the canvas
clear_button = tk.Button(root, text="Clear Canvas", command=clear_canvas)
clear_button.pack()
# Run the Tkinter event loop
root.mainloop()

In this example:

We create a Tkinter window and a canvas widget.

We draw some items on the canvas (a rectangle in this case) for demonstration purposes.

We define a function clear_canvas() that uses the delete("all") method to remove all items from the canvas.

We create a button that calls the clear_canvas() function when clicked.

Finally, we start the Tkinter event loop to display the window and handle user interactions.

When you click the "Clear Canvas" button, it will remove all items drawn on the canvas, effectively clearing it.

Was this helpful?

More Python discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Python Blogs

Guides, tips and career advice on Python from JanBask experts.