Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีวาดสเกลสีไล่ระดับจากแดงไปเขียวใน Tkinter

การไล่ระดับสี (color gradient) กำหนดช่วงของสีที่ขึ้นอยู่กับตำแหน่ง หากคุณต้องการสร้างสเกลรูปสี่เหลี่ยมในแอปพลิเคชันที่มีช่วงสีต่างๆ (gradient) สามารถทำตามขั้นตอนเหล่านี้:

  • สร้างรูปสี่เหลี่ยมด้วยวิดเจ็ต Canvas และกำหนดความกว้างและความสูง
  • กำหนดฟังก์ชันเพื่อเติมสีในช่วง สำหรับการเติมสี เราสามารถใช้ค่า hex ภายใน tuple ได้
  • วนลูปผ่านช่วงของสีและเติมสีในรูปสี่เหลี่ยมด้วยสีนั้นๆ

ตัวอย่าง

# 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()

ผลลัพธ์

การรันโค้ดด้านบนจะแสดงสเกลไล่ระดับสีที่มีช่วงสีบางช่วงที่กำหนดไว้

วิธีวาดสเกลสีไล่ระดับจากแดงไปเขียวใน Tkinter