问题描述
我需要使我的 tkinter 矩形透明.有人知道怎么做吗?
I need to make my tkinter rectangles transparent. Does anyone know how to do that?
我尝试指定 alpha=".5", opacity=".5"
,并且我尝试在颜色代码的末尾再添加两位数字:fill="#ff000066"
.这些东西似乎都不起作用,我找不到正确的语法.
I have tried to specify alpha=".5", opacity=".5"
, and I have tried to add two more digits in the end of the color code: fill="#ff000066"
. None of these things seem to work, I can't find the right syntax.
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()
这段代码给了我这个消息:_tkinter.TclError: unknown option "-alpha"
,所以这显然不是正确的方法.
This code gives me this message: _tkinter.TclError: unknown option "-alpha"
, so this is obviously not the right way to do it.
推荐答案
您可以使用透明图像来模拟结果.使用 Pillow
创建透明图像,然后使用 canvas.create_image(...)
绘制它.下面是一个示例代码:
You can use transparent image to simulate the result. Use Pillow
to create transparent image and then use canvas.create_image(...)
to draw it. Below is a sample code:
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()
和输出:
这篇关于如何使 tkinter 画布矩形透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!