I'm trying to create a translucent (RGBA) rectangle in Tkinter. I used the code snippet from this answer to make it, but I'm having trouble understanding what the array does here. They initially wanted to make multiple rectangles, so I understand why they would use it in that respect, but when I try to change the array to a variable that, in my understanding, would do the same, it stops showing the rectangle color.
Here is the (slightly modified) code with an array for the output:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
images = [] # to hold the newly created image
def create_rectangle(x1, y1, x2, y2, **kwargs): # x & y's dimensions
alpha = int(kwargs.pop('alpha') * 255)
fill = kwargs.pop('fill')
fill = root.winfo_rgb(fill) + (alpha,) # Returns a tuple of the color
image = Image.new('RGBA', (x2-x1, y2-y1), fill)
images.append(ImageTk.PhotoImage(image))
canvas.create_image(x1, y1, image=images[-1], anchor='nw')
canvas.create_rectangle(x1, y1, x2, y2, **kwargs)
canvas = Canvas(width=300, height=300)
canvas.pack()
create_rectangle(50, 50, 250, 150, fill='green', alpha=.5)
root.mainloop()
With its output:
And the same code with a variable instead of images[-1]
after image=
:
def create_rectangle(x1, y1, x2, y2, **kwargs): # x & y's dimensions
alpha = int(kwargs.pop('alpha') * 255)
fill = kwargs.pop('fill')
fill = root.winfo_rgb(fill) + (alpha,) # Returns a tuple of the color
image = Image.new('RGBA', (x2-x1, y2-y1), fill)
test_var = ImageTk.PhotoImage(image)
canvas.create_image(x1, y1, image=test_var, anchor='nw')
canvas.create_rectangle(x1, y1, x2, y2, **kwargs)
Which outputs:
If I print the type()
of both, I get the same result (<class 'PIL.ImageTk.PhotoImage'>
), and defining the same variable and appending it (images.append(test_var)
) gives me the correct result. It's only when the variable is used in canvas.create_image
that the bug appears.
Does anyone know what is happening?