Reputation: 996
I have made a function that change the black colour of an image in png (a black icon with transparent background) to the colour of the accent theme in windows.
I use this function to made all my icons match the colour interface of my window, but with this function, I need to manually call the function to the image, and then, pick the image and define as a PhotoImage
to put it as a Label
in tkinter.
The goal of this, is to make a method to define the main png (the black icon) as a dynamic colour image that can be used as a PhotoImage
, but even with the Image.TkPhotoImage
method of the PIL library, I haven't done it.
The code of my function is this:
def changeImageColorToAccentColor(imagename):
imagename = str(imagename)
accent = str(getAccentColor().lstrip('#'))
rcolor = int(str(accent[0:2]),16)
gcolor = int(str(accent[2:4]),16)
bcolor = int(str(accent[4:6]),16)
im = Image.open(str(imagename))
im = im.convert('RGBA')
data = np.array(im) # "data" is a height x width x 4 numpy array
red, green, blue, alpha = data.T # Temporarily unpack the bands for readability
# Replace white with red... (leaves alpha values alone...)
white_areas = (red == 0) & (blue == 0) & (green == 0) & (alpha == 255)
data[..., :-1][white_areas.T] = (rcolor, gcolor, bcolor) # Transpose back needed
im2 = Image.fromarray(data)
image1 = ImageTk.PhotoImage(im2)
return(image1)
And then, I define my Label in tkinter giving the image
option the function that returns the PhotoImage object.
icon = Label(image=changeImageColorToAccentColor('file.png'))
But it doesn't work for me, so, if this proof doesn't work, I won't be able to make the object.
Upvotes: 0
Views: 162
Reputation: 10542
You need ta save a reference to the PhotoImage
object. If it gets garbage collected the image won't show. Passing it ti the Label
as image
parameter does not save a reference automatically. If you do
im = changeImageColorToAccentColor('image2.png')
icon = Label(root, image=im)
the PhotoImage
object is saved as im
and the image will show.
Upvotes: 1