How can I vary a shape's alpha with Tkinter?

Neal Ehardt picture Neal Ehardt · Mar 18, 2013 · Viewed 9.4k times · Source

I have the following code that uses Tkinter to create a window and draw shapes on a canvas inside it.

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()

The rectangle sits on top of the two ovals. Is there any way that I can make the rectangle partially transparent (so the ovals' outlines can be seen)?

Answer

A. Rodas picture A. Rodas · Mar 18, 2013

I am not completely sure, but I think it is not possible to set a RGBA color as a fill color of a canvas item. However, you can give a try to the stipple option:

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