Tkinter create_image() 保留 PNG 透明度但 Button(image) 不

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

TkVersion = 8.6,Python 版本 3.7.3

我正在尝试使用 PNG 图像通过 tkinter 在 python 中创建一个按钮。图像的透明角是透明的,具体取决于我使用的是哪个小部件。似乎 canvas.create_image 是唯一保留透明度的小部件。

首先,我使用 create_image(0,0, image=button) 在 canvas 上添加了图像,效果很好 - 圆角是透明的。

但是当我尝试使用 Button()create_window() 小部件将其实现为实际按钮时,角落充满了白色。

button = ImageTk.PhotoImage(file="button.png")

canvas = tk.Canvas(width=200, heigh=200, borderwidth=0, highlightthickness=0)
canvas.grid()
canvas.create_rectangle(0,0,199,199, fill="blue")

canvas.create_image(0,0, image=button, anchor="nw")

[]

button = ImageTk.PhotoImage(file="button.png")

canvas = tk.Canvas(width=200, heigh=200, borderwidth=0, highlightthickness=0)
canvas.grid()
canvas.create_rectangle(0,0,199,199, fill="blue")

buttonWidget = tk.Button(root, image=button)
canvas.create_window(0,0, window=buttonWidget, anchor="nw")

如何使 PNG 按钮的边角透明?

这也是按钮图片:

您可以制作自己的自定义按钮 class,继承自 canvas,并像使用 Button() 一样使用它。我为您制作了一个,希望对您有所帮助。

自定义按钮Class:

将此 class 保存在一个单独的文件中作为 imgbutton.py,然后将其导入到您的主文件中。还要确保它与主文件位于同一目录中。或者您可以在导入后将其保留在主文件的顶部。

import tkinter as tk

class 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="+")

这是一个如何使用它的例子

import tkinter as tk
from imgbutton import Imgbutton    # Import the custom button class

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