score:0
If you are using a .png with import PIL
python is supporting the transparency.
However, within tkinter
the .Button
widget does not support transparency.
So what you will have is transparent image on top of a solid background.
If you are a windows user, your best bet is this solution:
score:1
The solution is a bit tricky as you need to go around using PIL but works. Just solved it after 2h of fighting.
You need to use PIL as an image loader and then pass the image to tkinter BUT with the usage of the root (main tk.Tk()
class object) - without that the image won't be visible as it's gone in the garbage collector, only image's space remains. Simplified code below:
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
button = tk.Button(self.left_menu)
button_load = Image.open('assets/search.png')
root.button_img = ImageTk.PhotoImage(button_load)
button.config(image=root.button_img)
button_1.pack(side='top')
score:3
To create an image that supports .png
transparency, you have to create a Canvas
and then create an image object using the canvas .create_image()
feature. Then bind an event to the canvas image using .tag_bind()
.
For example:
import tkinter as tk
from PIL import Image, ImageTk
def quitGame(event):
window.destroy()
window = tk.Tk()
window.geometry("500x500")
canvas = tk.Canvas(window, width = 300, height = 300)
canvas.pack()
#creating background
bgImage = ImageTk.PhotoImage(Image.open("Images/background.png"))
bg = canvas.create_image(0, 0, image=bgImage, anchor=tk.NW)
#creating button which supports png transparency
quitImage = ImageTk.PhotoImage(Image.open("Images/quitImage.png"))
quitButton = canvas.create_image(50, 50, image=quitImage)
canvas.tag_bind(quitButton, "<Button-1>", quitGame)
window.mainloop()
Credit To: stackoverflow.com