I have a Button
with a button image but when it is in my window the background of the button clashes with the background of the window. It is a .png image but tkinter
seems to want to keep the image as a quadrilateral by adding grey space. Is there a way to make the empty space of a button become transparent so that you are just left with the button image?
I am using Python 3.4.2 on Windows 8.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With