Home Articles

Tkinter图像透明度

Asked
Viewed 471 times
2

所以我有2张图片,我想在彼此之上显示 . 顶部的图像应该具有透明度,以便底部的图像可见 .

到目前为止,这是我的代码:

from Tkinter import *
import ttk
from PIL import Image, ImageTk

root = Tk()

face = Image.open("faces/face.gif")
eyes = Image.open("faces/eyes1.png")
face = face.convert("RGBA")
eyes = eyes.convert("RGBA")
facedatas = face.getdata()
eyesdatas = eyes.getdata()

newData = []
for item in eyesdatas:
    if item[0] == 255 and item[1] == 255 and item[2] == 255:
        newData.append((255, 255, 255, 0))
    else:
        newData.append(item)

eyes.putdata(newData)
eyes.save("eyes0.png", "PNG")

facepic = ImageTk.PhotoImage(face)
eyespic = ImageTk.PhotoImage(eyes)

label1 = Label(image=facepic)
label1.image = facepic
label1.grid(row = 0, column = 0)

label2 = Label(image=eyespic)
label2.image = eyespic
label2.grid(row = 0, column = 0)

root.mainloop()

这是我运行时得到的:

Eyes

当我想获得这个:

face and eyes

面部在底部,眼睛在顶部 .

2 Answers

  • 2

    试试这个

    from PIL import Image, ImageTk
    from Tkinter import Tk, Label
    
    root = Tk()
    
    def RBGAImage(path):
        return Image.open(path).convert("RGBA")
    
    face = RBGAImage("faces/face.gif")
    eyes = RBGAImage("faces/eyes1.png")
    
    face.paste(eyes, (0, 0), eyes)
    
    facepic = ImageTk.PhotoImage(face)
    
    label1 = Label(image=facepic)
    label1.grid(row = 0, column = 0)
    
    root.mainloop()
    

    我没有你的源图像,所以我不能确定它是否适用于它们 . 如果有任何问题,请提供两者的原件 .

  • 1

    您可以使用 Image.alpha_composite 创建新的合成图像 .

    from PIL import Image, ImageTk
    from Tkinter import Tk, Label
    
    root = Tk()
    
    def RBGAImage(path):
        return Image.open(path).convert("RGBA")
    
    face = RBGAImage("faces/face.gif")
    eyes = RBGAImage("faces/eyes1.png")
    
    c = Image.alpha_composite(face, eyes)
    
    facepic = ImageTk.PhotoImage(c)
    
    label1 = Label(image=facepic)
    label1.grid(row = 0, column = 0)
    
    root.mainloop()
    

Related