Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

python - Tkinter Image transparency

So I have 2 images that I would like to display on top of each other. The image on top should have transparency so that the one on the bottom is visible.

Here is my code so far:

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()

And here is what I get when I run it:

Eyes

When I would like to obtain this:

face and eyes

With the face in the bottom and the eyes on top.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

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()

I do not have both your source images, so I can not be sure it will work with them. Please provide the originals of both if there is any issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...