gpt4 book ai didi

python - 如何使 tkinter Canvas 多边形透明?

转载 作者:行者123 更新时间:2023-12-05 02:53:37 26 4
gpt4 key购买 nike

有没有更好的方法使多边形的填充透明,而不是使用点画?这是一个例子:

import tkinter as tk


class GUI:
def __init__(self, master, x, y):
self.master = master
self.canvas = tk.Canvas(master, width=x, height=y)
self.canvas.pack()
self.canvas.create_polygon(10, 10, 10, 20, 200, 300, 250, 150, 10, 10,
outline="green", fill="blue")
self.canvas.create_polygon(100, 10, 10, 40, 50, 300, 250, 400, 100, 10,
outline="green", fill="red", stipple="gray50")


x, y = 500, 500
root = tk.Tk()
gui = GUI(root, x, y)
root.mainloop()

我想让红色多边形的透明度变得逼真,就像任何给定 alpha 参数的软件一样。

最佳答案

我的解决方案灵感来自 this answer在类似的问题上,但对于矩形,而不是多边形。

不幸的是,Tkinter 不支持 RGBA,因此不可能只传递填充参数 fill="#ff000055"。相反,我们可以使用 PIL 创建包含矩形并具有 RGBA channel 的图像。

这是一个例子:

from tkinter import *
from PIL import Image, ImageDraw, ImageTk


def create_polygon(*args, **kwargs):
if "alpha" in kwargs:
if "fill" in kwargs:
# Get and process the input data
fill = root.winfo_rgb(kwargs.pop("fill"))\
+ (int(kwargs.pop("alpha") * 255),)
outline = kwargs.pop("outline") if "outline" in kwargs else None

# We need to find a rectangle the polygon is inscribed in
# (max(args[::2]), max(args[1::2])) are x and y of the bottom right point of this rectangle
# and they also are the width and height of it respectively (the image will be inserted into
# (0, 0) coords for simplicity)
image = Image.new("RGBA", (max(args[::2]), max(args[1::2])))
ImageDraw.Draw(image).polygon(args, fill=fill, outline=outline)

images.append(ImageTk.PhotoImage(image)) # prevent the Image from being garbage-collected
return canvas.create_image(0, 0, image=images[-1], anchor="nw") # insert the Image to the 0, 0 coords
raise ValueError("fill color must be specified!")
return canvas.create_polygon(*args, **kwargs)

images = [] # to hold the newly created image(s)

root = Tk()

canvas = Canvas(width=260, height=310)
canvas.pack()

create_polygon(10, 10, 10, 20, 200, 300, 250, 150, 10, 10, fill="blue", alpha=0.5)
create_polygon(150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200, fill="blue", alpha=0.2)

root.mainloop()

关于python - 如何使 tkinter Canvas 多边形透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62117203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com