如何使用 Tkinter 繪製一個從紅色漸變到綠色的刻度?
顏色漸變定義了位置相關顏色的範圍。具體來說,如果你想在包含某些顏色範圍(漸變)的應用程式中建立一個矩形刻度,那麼我們可以按照以下步驟操作 −
使用 canvas 元件建立一個矩形,並定義其寬度和高度。
定義一個函式來填充顏色範圍。為了填充顏色,我們可以使用元組中的十六進位制值。
迭代顏色的範圍,並將矩形用它填充。
示例
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the window
win.geometry("700x350")
win.title("Gradient")
# Define a function for filling the rectangle with random colors
def rgb(r, g, b):
return "#%s%s%s" % tuple([hex(c)[2:].rjust(2, "0")
for c in (r, g, b)])
# Define gradient
gradient = Canvas(win, width=255 * 2, height=25)
gradient.pack()
# Iterate through the color and fill the rectangle with colors(r,g,0)
for x in range(0, 256):
r = x * 2 if x < 128 else 255
g = 255 if x < 128 else 255 - (x - 128) * 2
gradient.create_rectangle(x * 2, 0, x * 2 + 2, 50, fill=rgb(r, g, 0), outline=rgb(r, g, 0))
win.mainloop()輸出
執行以上程式碼將顯示一個刻度漸變,其中定義了一些顏色範圍。

廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP