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

时间:2019-04-22 09:20:28

标签: python tkinter transparency tkinter-canvas

TkVersion = 8.6,Python版本3.7.3

我正在尝试使用tkinter在python中使用PNG图片创建按钮。图像的透明角是透明的,具体取决于我使用的窗口小部件。看来canvas.create_image是唯一保持透明度的小部件。

首先,我使用create_image(0,0, image=button)将图像添加到画布上,并且效果很好-圆角是透明的。

但是,当我尝试使用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")

works []

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

doesnt work

如何使PNG按钮角透明?

这也是按钮图像: button

1 个答案:

答案 0 :(得分:1)

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

自定义按钮类别:

将此类作为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()