Canvas widget ใน Tkinter ไม่รองรับ alpha channel โดยตรง ต้องสร้างภาพ RGBA ด้วย Pillow แล้ววาดบน Canvas
หลักการ
- สร้างฟังก์ชัน
create_rectangleรับพารามิเตอร์ alpha - คำนวณค่า alpha (0-1) เป็น 0-255
- สร้างภาพ RGBA ด้วย
Image.new('RGBA', size, color+alpha) - วาดภาพบน Canvas ด้วย
create_image
ตัวอย่างโค้ด
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(60, 90, 310, 250, fill="red", alpha=.3)
canvas.pack()
win.mainloop()
ผลลัพธ์
สี่เหลี่ยมผืนผ้า 2 ชิ้นทับซ้อนกัน มีความโปร่งใส 30% สามารถมองเห็นสีทับซ้อนได้
