Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter, overlay foreground image on top of a background image with transparency

I have 2 images, in png format. The second image, is a shape with transparent background.

First image:

enter image description here

Second image:

enter image description here

I cannot make the second image on top of the first at given coordinates (x,y) with the first image visible through the transparent zone of the second image.

Result desired:

enter image description here

import Tkinter
import Image, ImageTk

# open an image
head = Image.open('background2.png')
hand = Image.open('foreground2.png')
root = Tkinter.Tk()  # A root window for displaying objects

head.paste(hand,(20,20))

# Convert the Image object into a TkPhoto object
tkimage = ImageTk.PhotoImage(head)

root.mainloop() # Start the GUI

An empty tk window is displayed.

like image 703
AJN Avatar asked Oct 01 '22 17:10

AJN


1 Answers

Thanks Bryan. Got it, in addition to label, the issue of transparency resolved from another question here (same foregound image used as a mask)

I guess, this is what cost me -2 points :-|

Now it works as expected.

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

root = Tkinter.Tk()  # A root window for displaying objects
# open image
imageHead = Image.open('head.png')
imageHand = Image.open('hand.png')

imageHead.paste(imageHand, (20, 40), imageHand)
# Convert the Image object into a TkPhoto object
tkimage = ImageTk.PhotoImage(imageHead)

panel1 = Label(root, image=tkimage)
panel1.grid(row=0, column=2, sticky=E)
root.mainloop()  # Start the GUI
like image 165
AJN Avatar answered Oct 04 '22 20:10

AJN