Transparent Backgrounds on Buttons in Tkinter

20,583

Solution 1

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()

Solution 2

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')
Share:
20,583
Mitra0000
Author by

Mitra0000

Updated on February 07, 2022

Comments

  • Mitra0000
    Mitra0000 over 2 years

    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.

  • martineau
    martineau over 2 years
    I don't see this as addressing the OP's question at all.
  • martineau
    martineau over 2 years
    There's really no need to use the PIL to do this because tkinter.PhotoImage can read .png as well as .gif, .pgm, and .ppm formatted files. See my answer to a related post which illustrates this (but is otherwise based on yours).