Search code examples
pythonbuttontkinterpngtransparency

Tkinter: Adding Image with transparent background to Button


hope you're all doing well. I've got a problem I hope you can help with.

I'm trying to build a board game in tkinter. This will have different shaped tiles being placed in squares on top of a background image. I have managed to add in the background with tk.PhotoImage and tk.Label, and correctly resized the image of the tile with ImageTk.PhotoImage.

However, when I place the tile on the board, all transparency is lost and replaced with monotone grey.

enter image description here

Minimal Code:

from PIL import Image,ImageTk
import tkinter as tk

def tile_push():
    pass

# Create background image
root = tk.Tk()
root.geometry("390x500") # Size of background board
background_image = tk.PhotoImage(file="Gameboard.png")
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

# Create button
im = Image.open("Chick.png").resize((100,100))
image_player_1 = ImageTk.PhotoImage(im)
b = tk.Button(root, image=image_player_1, command=tile_push, borderwidth=0, highlightthickness=0)
b.place(x=140, y=258, width=115, height=115)
tk.mainloop()

A similar question on SO shows how to set the background as black, but I need the background to be transparent.

Any help will be greatly appreciated!


Solution

  • Thanks for the support acw, I've managed to get it going now. This is what I did:

    from PIL import Image,ImageTk
    import tkinter as tk
    
    def tile_push(*args, **kwargs):
        print("It's alive!")
    
    # Create background image
    root = tk.Tk()
    root.geometry("390x500") # Size of background board
    canvas = tk.Canvas(root, width=390, height=500)
    canvas.place(x=0,y=0)
    background_image = tk.PhotoImage(file="Gameboard.png")
    canvas.create_image((0,0), anchor="nw", image=background_image)
    
    # Create button
    im = Image.open("Chick.png").resize((115,115))
    imTk =  ImageTk.PhotoImage(im)
    chick = canvas.create_image((140,258), anchor="nw", image=imTk)
    canvas.tag_bind(chick, '<Button-1>', tile_push)
    tk.mainloop()