キャンバスの図形の削除

2022/02/06

Python3.9.9

canvas.delete(id_or_tag)


図形をクリックして削除するサンプル

import tkinter

class CanvasOval:
    canvas = None

    def __init__(self, x0, y0, x1, y1, **key):
        self.id = self.canvas.create_oval(x0, y0, x1, y1, **key)
        self.canvas.tag_bind(self.id, '<1>', self.delete)

    def delete(self, event):
        self.canvas.delete(self.id)


class Frame(tkinter.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.cvs = tkinter.Canvas(self,width="200", height="200", bg="white")
        self.cvs.grid(row=0, column=0)

        CanvasOval.canvas=self.cvs
        CanvasOval(40, 40, 50, 50, fill="red", width=0)
        CanvasOval(130, 130, 170, 170, fill="red", width=0)

if __name__ == '__main__':
    f = Frame()
    f.pack()
    f.mainloop()

図形削除