有没有比使用点画法更透明的多边形填充方式了?这里是一个例子:
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 args fill="#ff000055"
是不可能的。相反,我们可以使用PIL创建包含矩形并具有RGBA通道的图像。
这里是一个例子:
from tkinter import *
from PIL import Image, ImageDraw, ImageTk
def create_polygon(*args, **kwargs):
if "fill" in kwargs and "alpha" in kwargs:
fill = root.winfo_rgb(kwargs.pop("fill"))\
+ (int(kwargs.pop("alpha") * 255),)
outline = kwargs.pop("outline") if "outline" in kwargs else None
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))
canvas.create_image(0, 0, image=images[-1], anchor="nw")
else:
canvas.create_polygon(*args, **kwargs)
images = [] # to hold the newly created image(s)
root = Tk()
canvas = Canvas(width=500, height=500)
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()
注意:此解决方案尚未完全准备好,我将在最终版本中对其进行更新。