Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent Backgrounds on Buttons in Tkinter

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.

like image 782
Mitra0000 Avatar asked Nov 09 '22 15:11

Mitra0000


1 Answers

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()
like image 142
deezRam Avatar answered Nov 14 '22 22:11

deezRam