2 years ago

#41707

test-img

Will Jordan

canvas.delete() only working as expected once for deleting rectangle

So I have this piece of code that I took from an answer by @acw1668 which can create and place transparent rectangles onto a canvas.

However, I needed to be able to delete them so that they can be moved and replaced. Initially, I thought canvas.delete(tag) was the way to go and added tags to the relevant lines in the function, but it does not behave as expected.

I also tried assigning the object to a variable and using canvas.delete(variable) but that would have been hard to execute as the rectangle was created in a function, that is called by a function, that cannot take arguments.

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

images = []  # to hold the newly created image

def remove(tag):
    canvas.delete(tag):

def create_rectangle(x1, y1, x2, y2, tag, **kwargs):
    if 'alpha' in kwargs:
        alpha = int(kwargs.pop('alpha') * 255)
        fill = kwargs.pop('fill')
        fill = root.winfo_rgb(fill) + (alpha,)
        image = Image.new('RGBA', (x2-x1, y2-y1), fill)
        images.append(ImageTk.PhotoImage(image))
        canvas.create_image(x1, y1, image=images[-1], anchor='nw', tags=tag)
    canvas.create_rectangle(x1, y1, x2, y2, tags=tag, **kwargs)

canvas = Canvas(width=300, height=200)
canvas.pack()

create_rectangle(80, 80, 150, 120, "1", fill='#800000', alpha=.8)
time.sleep(1) # Ik not to use in tkinter like this but just used to try and show what my actual program is like
remove("1")

root.mainloop()

But basically when I press a button that calls remove() the outline is not removed ever, and the fill (coloured part) is removed the first time remove is called, but when a new rectangle is created the remove button then does nothing. I'm not sure why it would work once but not again but I would love this to work as then I can alter this function to work for my program.

python

tkinter

tkinter-canvas

0 Answers

Your Answer

Accepted video resources