Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Using delete() Method
The delete() method removes canvas objects by their ID. When you create a line using create_line(), it returns an ID that you can later use to delete that specific line.
Example
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
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define a function to delete the shape
def on_click():
canvas.delete(line)
# Create a canvas widget
canvas = Canvas(win, width=500, height=300)
canvas.pack()
# Add a line in canvas widget
line = canvas.create_line(100, 200, 200, 35, fill="red", width=10)
# Create a button to delete the line
Button(win, text="Delete Shape", command=on_click).pack()
win.mainloop()
The output of the above code is ?
A window with a red line and a "Delete Shape" button. Clicking the button removes the line from the canvas.
Deleting Multiple Lines
You can also delete multiple lines by storing their IDs in a list and deleting them one by one ?
from tkinter import *
win = Tk()
win.geometry("700x350")
# Store line IDs in a list
lines = []
def add_line():
line_id = canvas.create_line(50, 50, 200, 200, fill="blue", width=3)
lines.append(line_id)
def delete_all_lines():
for line_id in lines:
canvas.delete(line_id)
lines.clear()
canvas = Canvas(win, width=500, height=300)
canvas.pack()
Button(win, text="Add Line", command=add_line).pack()
Button(win, text="Delete All Lines", command=delete_all_lines).pack()
win.mainloop()
Key Points
-
create_line()returns an ID that can be used withdelete() - You can delete specific lines by their ID or use
"all"to delete everything - Store line IDs in a list to manage multiple lines
- Use
canvas.delete("all")to clear the entire canvas
Conclusion
Use the delete() method with the line ID to remove specific lines from a tkinter Canvas. Store multiple IDs in a list for batch deletion operations.
