如何使Tkinter画布矩形透明?

Jån*_*nny 6 python transparency tkinter colors

我需要使tkinter矩形透明。有谁知道这是怎么做到的吗?

我尝试指定alpha=".5", opacity=".5",并且尝试在颜色代码的末尾再添加两个数字:fill="#ff000066"。这些东西似乎都不起作用,我找不到正确的语法。

import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=800, height=600)
canvas.pack()

canvas.create_rectangle(50, 50, 100, 100, fill="#ff0000", alpha=0.5)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

这段代码给了我这个信息:_tkinter.TclError: unknown option "-alpha",所以显然这不是正确的方法。

小智 11

在画布中,如果您希望某些小部件透明,只需让 fill 参数为空:

fill=""
Run Code Online (Sandbox Code Playgroud)


acw*_*668 7

您可以使用透明图像来模拟结果。使用Pillow创建透明的图像,然后用canvas.create_image(...)画它。下面是一个示例代码:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

images = []  # to hold the newly created image

def create_rectangle(x1, y1, x2, y2, **kwargs):
    if 'alpha' in kwargs:
        alpha = int(kwargs.pop('alpha') * 255)
        fill = kwargs.pop('fill')
        fill = root.winfo_rgb(fill) + (alpha,)
        image = Image.new('RGBA', (x2-x1, y2-y1), fill)
        images.append(ImageTk.PhotoImage(image))
        canvas.create_image(x1, y1, image=images[-1], anchor='nw')
    canvas.create_rectangle(x1, y1, x2, y2, **kwargs)

canvas = Canvas(width=300, height=200)
canvas.pack()

create_rectangle(10, 10, 200, 100, fill='blue')
create_rectangle(50, 50, 250, 150, fill='green', alpha=.5)
create_rectangle(80, 80, 150, 120, fill='#800000', alpha=.8)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

并输出:

在此处输入图片说明

  • 您需要安装“Pillow”模块。 (6认同)