Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ทำให้สี่เหลี่ยมผืนผ้าใน Tkinter Canvas โปร่งใส (Transparent)

Canvas ไม่รองรับ alpha โดยตรง ต้องสร้างภาพ RGBA ด้วย Pillow คล้ายวิธีการกับรูปทรงทั่วไป

ตัวอย่างโค้ด

from tkinter import *
from PIL import Image, ImageTk

win = Tk()
win.geometry("700x350")

images = []

def create_rectangle(x, y, a, b, **options):
    if 'alpha' in options:
        alpha = int(options.pop('alpha') * 255)
        fill = options.pop('fill')
        fill = win.winfo_rgb(fill) + (alpha,)
        image = Image.new('RGBA', (a-x, b-y), fill)
        images.append(ImageTk.PhotoImage(image))
        canvas.create_image(x, y, image=images[-1], anchor='nw')
    canvas.create_rectangle(x, y, a, b, **options)

canvas = Canvas(win)
create_rectangle(50, 110, 300, 280, fill="blue", alpha=.3)
create_rectangle(40, 90, 420, 250, fill="red", alpha=.1)
canvas.pack()

win.mainloop()

ผลลัพธ์

แสดงสี่เหลี่ยมผืนผ้าหลายชิ้นที่มีความโปร่งใสต่างกัน ทับซ้อนกันได้

ทำให้สี่เหลี่ยมผืนผ้าใน Tkinter Canvas โปร่งใส (Transparent)