How can I change the alpha form with Tkinter?

I have the following code that Tkinter uses to create a window and draw shapes on the 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 is located on top of two ovals. Is there a way so that I can make the rectangle partially transparent (so that the oval contours can be seen)?

+5
source share
3 answers

You cannot change the alpha elements on the canvas.

+4
source

I'm not quite sure, but I think it's impossible to set the RGBA color as the fill color of the canvas element. However, you can try the parameter stipple:

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

The idea is to create a rectangular png image with translucent colors. Then use create_image instead of create_rectangle.

+2
source

All Articles