Widget Canvas มีกรณีการใช้งานมากในการพัฒนา GUI สร้างรูปทรง, กราฟิก, ภาพ ฯลฯ วาดเส้นใน Canvas ใช้เมธอด create_line(x,y,x1,y1, **options) ใน Tkinter วาดเส้นได้ 2 แบบ: เส้นธรรมดาและเส้นประ
หากต้องการให้แอปพลิเคชันลบเส้นที่สร้าง ใช้เมธอด delete()
ตัวอย่าง
ตัวอย่างลบเส้นที่กำหนดใน 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 button
Button(win, text="Delete Shape", command=on_click).pack()
win.mainloop()
ผลลัพธ์
รันโค้ด จะแสดงหน้าต่างพร้อมปุ่มและรูปทรงใน canvas

คลิกปุ่ม "Delete Shape" เพื่อลบเส้นที่แสดงจาก canvas