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

2024-05-16 17:36:43 发布

您现在位置:Python中文网/ 问答频道 /正文

TkVersion=8.6,Python版本3.7.3

我试图用python中的tkinter创建一个使用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[]

^{pr2}$

doesnt work

如何使PNG按钮角透明?在

下面是按钮图像: button


Tags: 图像image版本png部件tkinter画布create
1条回答
网友
1楼 · 发布于 2024-05-16 17:36:43

您可以创建从canvas继承的自定义按钮类,并像使用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="+")

下面是一个如何使用它的示例

^{pr2}$

相关问题 更多 >