How to delete lines from a Python tkinter canvas?


The Canvas widget has many use-cases in GUI application development. We can use a Canvas widget to draw shapes, creating graphics, images, and many other things. To draw a line in Canvas, we can use create_line(x,y,x1,y1, **options) method. In Tkinter, we can draw two types of lines − simple and dashed.

If you want your application to delete the created lines, then you can use the delete() method.


Let us have a look at the example where we will delete the line defined in the Canvas widget.

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window

# Set the size of the tkinter window

# Define a function to delete the shape
def on_click():

# Create a canvas widget
canvas=Canvas(win, width=500, height=300)

# Add a line in canvas widget
line=canvas.create_line(100,200,200,35, fill="red", width=10)

# Create a button to delete the button
Button(win, text="Delete Shape", command=on_click).pack()



If we run the above code, it will display a window with a button and a shape in the canvas.

Now, click the "Delete Shape" button to delete the displayed line from the canvas.

Published on 06-Aug-2021 06:34:16