如何使Tkinter畫布矩形透明?


canvas部件是Tkinter庫中最通用的部件之一。通常,它用於在任何應用程式中繪製形狀、動畫物件和建立複雜的圖形。要建立像矩形這樣的形狀,我們使用create_rectangle(x,y, x+ width, y+ height, **options)方法。我們可以透過新增諸如寬度、高度、填充和背景、邊框寬度等屬性來配置畫布上的專案。

畫布中的alpha屬性定義了畫布專案的透明度。但是,此屬性在Tkinter庫中不可用;因此,我們必須定義一個函式來為形狀提供透明度屬性。建立透明度屬性函式的步驟如下:

  • 定義一個內建函式create_rectangle(x,y,a,b, **options)
  • 計算必須提供給形狀的每種顏色(RGB)的alpha值。
  • 使用pop()刪除形狀中預定義的alpha值(如果適用)。
  • 使用winfo_rgb()計算區域中的形狀顏色,並將alpha值新增到形狀中。
  • 由於新建立的形狀將具有不同的顏色和背景,因此必須將其用作影像。
  • 影像可以輕鬆地顯示在畫布上。

示例

# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame
win= Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Store newly created image
images=[]

# Define a function to make the transparent rectangle
def create_rectangle(x,y,a,b,**options):
   if 'alpha' in options:
      # Calculate the alpha transparency for every color(RGB)
      alpha = int(options.pop('alpha') * 255)
      # Use the fill variable to fill the shape with transparent color
      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)
# Add a Canvas widget
canvas= Canvas(win)

# Create a rectangle in canvas
create_rectangle(50, 110,300,280, fill= "blue", alpha=.3)
create_rectangle(40, 90, 420, 250, fill= "red", alpha= .1)
canvas.pack()

win.mainloop()

輸出

執行以上程式碼將在畫布上顯示多個透明矩形。

更新於:2021年6月8日

9K+ 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告