如何在Tkinter中改变形状的透明度?

12 投票
4 回答
13285 浏览
提问于 2025-04-17 19:27

我有一段代码,它使用Tkinter来创建一个窗口,并在里面的画布上绘制形状。

from Tkinter import *

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent 
        self.initUI()

    def initUI(self):

        self.parent.title("Colors")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)

        canvas.create_oval(10, 10, 80, 80, outline="red", fill="green", width=2)
        canvas.create_oval(110, 10, 210, 80, outline="#f11", fill="#1f1", width=2)
        canvas.create_rectangle(20, 50, 300, 100, outline="black", fill="red", width=2)

        canvas.pack(fill=BOTH, expand=1)


if __name__ == '__main__':
    root = Tk()
    ex = Example(root)
    root.geometry("400x400+100+100") # WIDTHxHEIGHT+X+Y
    root.mainloop()

这个矩形是在两个椭圆的上面。有没有办法让我把这个矩形变得半透明(这样就可以看到椭圆的轮廓)呢?

4 个回答

5

这个想法是制作一个带有半透明颜色的矩形PNG图片。然后用create_image来代替create_rectangle。

17

我不太确定,但我觉得不能把RGBA颜色作为画布项目的填充颜色。不过,你可以试试stipple这个选项:

canvas.create_rectangle(20, 50, 300, 100, outline="black", fill="red", width=2, stipple="gray50")
7

你不能改变画布上物品的透明度。

撰写回答