如何使用 Tkinter 更改形狀的 alpha?
畫布小部件是 tkinter 庫中多邊小部件之一,用於為任何應用程式提供影像。它可用於繪製形狀、影像、動畫物件或任何複雜影像。形狀的alpha 屬性定義瞭如果我們為任何形狀指定alpha 值,則它必須在其父視窗方面具有一定的透明行為。
若要定義 alpha 屬性,我們必須假設每個形狀都含有一些顏色,每當我們為形狀提供 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(60, 90,310,250, fill= "red", alpha=.3)
canvas.pack()
win.mainloop()輸出
執行以上程式碼檢視 alpha 屬性如何在形狀中變化的。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP