Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 835
Neal Ehardt Avatar asked Mar 18 '13 01:03

Neal Ehardt


People also ask

How do I change the outline width in tkinter?

To change the thickness of the outline, provide a border or outline to a rectangle, define the width property in the constructor and assign it an integer value. You can also define the outline property to set a color to the outline of the oval.

What is Textvariable in tkinter?

textvariable is used to provide value through a variable. value can be Integer or String. for integer : IntVar() keyword is used. for String: StringVar() keyword is used.

What is pack method in tkinter?

pack is the easiest Layout Manager to code with in Tkinter. Instead of declaring the precise location of a widget, the pack() method declares the position of widgets in relation to each other. However, pack() is limited in precision compared to place() and grid() which feature absolute positioning.


2 Answers

You cannot change the alpha of items on a canvas.

like image 195
Bryan Oakley Avatar answered Nov 06 '22 03:11

Bryan Oakley


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")
like image 29
A. Rodas Avatar answered Nov 06 '22 02:11

A. Rodas