我做了一个函数,可以将png中的图像的黑色(带有透明背景的黑色图标)更改为Windows中的重音主题的颜色。
我使用此功能使我所有的图标都与窗口的颜色界面匹配,但是使用此功能,我需要手动调用该功能到图像,然后选择图像并定义为PhotoImage
它是tkinter中的Label
。
这样做的目的是要提供一种方法,以将主png(黑色图标)定义为可以用作PhotoImage
的动态彩色图像,甚至可以使用PIL的Image.TkPhotoImage
方法库,我还没有做。
我的函数的代码是这样的:
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)
然后,我在tkinter中定义我的Label,为image
选项提供返回PhotoImage对象的功能。
icon = Label(image=changeImageColorToAccentColor('file.png'))
但这对我不起作用,因此,如果此证明不起作用,我将无法制造该物体。
答案 0 :(得分:1)
您需要保存对PhotoImage
对象的引用。如果收集到垃圾,该图像将不会显示。将其传递给Label
作为image
参数不会自动保存引用。如果你这样做
im = changeImageColorToAccentColor('image2.png')
icon = Label(root, image=im)
PhotoImage
对象另存为im
,图片将显示。