How to make a tkinter canvas rectangle transparent?

后端 未结 2 1816
忘掉有多难
忘掉有多难 2020-12-10 06:06

I need to make my tkinter rectangles transparent. Does anyone know how to do that?

I have tried to specify alpha=\".5\", opacity=\".5\", and I have trie

相关标签:
2条回答
  • 2020-12-10 06:07

    In a canvas if you want some widget to be transparent, simply let the fill parameter be empty:

    fill=""
    
    0 讨论(0)
  • 2020-12-10 06:32

    You can use transparent image to simulate the result. Use Pillow to create transparent image and then use canvas.create_image(...) to draw it. Below is a sample code:

    from tkinter import *
    from PIL import Image, ImageTk
    
    root = Tk()
    
    images = []  # to hold the newly created image
    
    def create_rectangle(x1, y1, x2, y2, **kwargs):
        if 'alpha' in kwargs:
            alpha = int(kwargs.pop('alpha') * 255)
            fill = kwargs.pop('fill')
            fill = root.winfo_rgb(fill) + (alpha,)
            image = Image.new('RGBA', (x2-x1, y2-y1), fill)
            images.append(ImageTk.PhotoImage(image))
            canvas.create_image(x1, y1, image=images[-1], anchor='nw')
        canvas.create_rectangle(x1, y1, x2, y2, **kwargs)
    
    canvas = Canvas(width=300, height=200)
    canvas.pack()
    
    create_rectangle(10, 10, 200, 100, fill='blue')
    create_rectangle(50, 50, 250, 150, fill='green', alpha=.5)
    create_rectangle(80, 80, 150, 120, fill='#800000', alpha=.8)
    
    root.mainloop()
    

    And the output:

    0 讨论(0)
提交回复
热议问题