如何使用 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