从PIL在tkinter中调用图像而不保存它

时间:2018-12-13 13:19:52

标签: python tkinter python-imaging-library

我做了一个函数,可以将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'))

但这对我不起作用,因此,如果此证明不起作用,我将无法制造该物体。

1 个答案:

答案 0 :(得分:1)

您需要保存对PhotoImage对象的引用。如果收集到垃圾,该图像将不会显示。将其传递给Label作为image参数不会自动保存引用。如果你这样做

im = changeImageColorToAccentColor('image2.png')
icon = Label(root, image=im)

PhotoImage对象另存为im,图片将显示。

相关问题