Skip to content Skip to sidebar Skip to footer

Delete Method On Canvas Tkinter

Trying to delete a random shape on canvas by clicking the 'remove rect' button created. but my method doesn't seem to work. I keep getting this error, must be small but I can't see

Solution 1:

You have to keep track of the rectangles you are creating in a collection; then extract the id from the collection in order to remove a rectangle.

here, I created a list to aggregate the ids of the rectangle created: self.canvas.create_rectangle(0, 0, w, h, fill='green') returns an id number that is stored in the collection.

Upon calling the delete method, the id from the last created rectangle is retrieved (and removed from the collection) and used to remove the rectangle from the canvas.

import tkinter as tk
import random
root = tk.Tk()

classRecta:

    def__init__(self, height=60, width=80):
        self.height = height
        self.width = width
        self.create_buttons()
        self.canvas = tk.Canvas(root)
        self.canvas.pack()
        self.rects = []

    defcreate_buttons(self):
        self.frame = tk.Frame(root, bg='grey', width=400, height=40)
        self.frame.pack(fill='x')

        self.button1 = tk.Button(self.frame, text='Add Rect', command=self.randomRects)
        self.button1.pack(side='left', padx=10)
        self.button2 = tk.Button(self.frame, text='Remove Rect', command=self.removeRects)
        self.button2.pack(side='left')

    defremoveRects(self):
        iflen(self.rects) > 0:
            self.canvas.delete(self.rects.pop())

    defrandomRects(self):
        w = random.randrange(300)
        h = random.randrange(200)
        self.rects.append(self.canvas.create_rectangle(0, 0, w, h, fill='green'))


tes = Recta()
root.mainloop()

Here is the same code with a * import!

from tkinter import *
import random
root = Tk()

classRecta:

    def__init__(self, height=60, width=80):
        self.height = height
        self.width = width
        self.create_buttons()
        self.canvas = Canvas(root)
        self.canvas.pack()
        self.rects = []

    defcreate_buttons(self):
        self.frame = Frame(root, bg='grey', width=400, height=40)
        self.frame.pack(fill='x')

        self.button1 = Button(self.frame, text='Add Rect', command=self.randomRects)
        self.button1.pack(side='left', padx=10)
        self.button2 = Button(self.frame, text='Remove Rect', command=self.removeRects)
        self.button2.pack(side='left')

    defremoveRects(self):
        iflen(self.rects) > 0:
            self.canvas.delete(self.rects.pop())

    defrandomRects(self):
        w = random.randrange(300)
        h = random.randrange(200)
        self.rects.append(self.canvas.create_rectangle(0, 0, w, h, fill='green'))


tes = Recta()
root.mainloop()

Post a Comment for "Delete Method On Canvas Tkinter"