Tkinter create_image() retains PNG transparency but Button(image) does not Tkinter create_image() retains PNG transparency but Button(image) does not tkinter tkinter

Tkinter create_image() retains PNG transparency but Button(image) does not


You can make your own custom button class inherited from canvas and use it just like you use Button(). I made one for you hopefully you find it helpful.

Custom Button Class:

Save this class in a separate file as imgbutton.py and then import it to your main file. Also make sure it is in the same directory as the main file is in. Or you can just keep it on the top of the main file after your imports.

import tkinter as tkclass Imgbutton(tk.Canvas):    def __init__(self, master=None, image=None, command=None, **kw):        # Declared style to keep a reference to the original relief        style = kw.get("relief", "groove")                if not kw.get('width') and image:            kw['width'] = image.width()        else: kw['width'] = 50        if not kw.get('height') and image:            kw['height'] = image.height()        else: kw['height'] = 24        kw['relief'] = style        kw['borderwidth'] = kw.get('borderwidth', 2)        kw['highlightthickness'] = kw.get('highlightthickness',0)        super(Imgbutton, self).__init__(master=master, **kw)        self.set_img = self.create_image(kw['borderwidth'], kw['borderwidth'],                 anchor='nw', image=image)        self.bind_class( self, '<Button-1>',                     lambda _: self.config(relief='sunken'), add="+")        # Used the relief reference (style) to change back to original relief.        self.bind_class( self, '<ButtonRelease-1>',                     lambda _: self.config(relief=style), add='+')        self.bind_class( self, '<Button-1>',                     lambda _: command() if command else None, add="+")

Here is an Example how to use it

import tkinter as tkfrom imgbutton import Imgbutton    # Import the custom button classroot = tk.Tk()root['bg'] = 'blue'but_img = tk.PhotoImage(file='button.png')but = Imgbutton(root, image=but_img, bg='blue',             command=lambda: print("Button Image"))but.pack(pady=10)root.mainloop()