Reputation: 55
So I have 2 images, 1 image is supposed to be the background and the other 1 is just an image of a character. I am able to put one image over the other but the image has white borders even though it's a PNG file.
This is how I want it to look like:
Here are the two separte images: https://i.sstatic.net/DX7N6.jpg Sorry that I didnt post the images directly but I can not since I do no have 10 reputation points.
I've tried converting it to RGBA but same thing happened.
from tkinter import *
from PIL import Image
root = Tk()
root.title("Game")
background = PhotoImage(file="back.png")
backgroundlabel = Label(root, image=background)
backgroundlabel.pack()
character = PhotoImage(file="hero.png")
characterlabel = Label(root, image=character)
characterlabel.place(x=0,y=0)
root.mainloop()
Upvotes: 4
Views: 9847
Reputation: 869
You just need to use the canvas
widget in Tkinter. Only the canvas widget supports transparency. This has to do with how Tkinter draws the display. As of right now, your code is just overlaying two images. Tkinter does not know how to compose them with transparency unless you use the canvas widget.
See the following code:
from tkinter import *
from PIL import Image
root = Tk()
root.title("Game")
frame = Frame(root)
frame.pack()
canvas = Canvas(frame, bg="black", width=700, height=400)
canvas.pack()
background = PhotoImage(file="background.png")
canvas.create_image(350,200,image=background)
character = PhotoImage(file="hero.png")
canvas.create_image(30,30,image=character)
root.mainloop()
All I did was download the images you provided. I did not modify the images. So, the bottom line is that you just need to use the canvas widget.
Voilà!
Note: The question asked is a duplicate of How do I make Tkinter support PNG transparency?
Upvotes: 6