在 Tkinter 中绘制从红色到绿色的比例尺

Draw a scale which ranges from red to green in Tkinter

我想画一个从红到绿的比例尺。我设法做了一个从绿色到黄色的比例。现在我有 2 种可能的解决方案:

如何实施第二个解决方案?

这是我从绿色到黄色的代码。你可以测试一下。

import tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        f = GradientFrame(root)
        f.pack(fill="both", expand=True)

class GradientFrame(tk.Canvas):
'''A gradient frame which uses a canvas to draw the background'''
    def __init__(self, parent, borderwidth=1, relief="sunken"):
    tk.Canvas.__init__(self, parent, borderwidth=borderwidth, relief=relief)
        self._color1 = "green"
        self._color2 = "yellow"
        self._color3 = "red"
        self.bind("<Configure>", self._draw_gradient)

def _draw_gradient(self, event=None):
    '''Draw the gradient'''
    self.delete("gradient")
    width = 200
    height = 50
    limit = width
    (r1,g1,b1) = self.winfo_rgb(self._color1)
    (r2,g2,b2) = self.winfo_rgb(self._color2)
    (r3,g3,b3) = self.winfo_rgb(self._color3)
    r_ratio = float((r2-r1)) / limit
    g_ratio = float((g2-g1)) / limit
    b_ratio = float((b2-b1)) / limit

    for i in range(limit):
        nr = int(r1 + (r_ratio * i))
        ng = int(g1 + (g_ratio * i))
        nb = int(b1 + (b_ratio * i))
        color = "#%4.4x%4.4x%4.4x" % (nr,ng,nb)
        self.create_line(0,i,height,i, tags=("gradient",), fill=color)
    self.lower("gradient")

    for i in range(limit):
        nr = int(r1 + (r_ratio * i))
        ng = int(g1 + (g_ratio * i))
        nb = int(b1 + (b_ratio * i))
        color = "#%4.4x%4.4x%4.4x" % (nr,ng,nb)
        self.create_line(0,i,height,i, tags=("gradient",), fill=color)
    self.lower("gradient")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

没有上述代码的概括或一般美学,我在这里为您提供一个简单的解决方案(针对红色到绿色渐变实现):

import tkinter

def rgb(r, g, b):
    return "#%s%s%s" % tuple([hex(c)[2:].rjust(2, "0") for c in (r, g, b)])

root = tkinter.Tk()
root.title("Gradient")

gradient1 = tkinter.Canvas(root, width=255*2, height=50)
gradient1.pack()

gradient2 = tkinter.Canvas(root, width=255*2, height=50)
gradient2.pack()

for x in range(0, 256):
    r = x
    g = 255-x
    gradient1.create_rectangle(x*2, 0, x*2 + 2, 50, fill=rgb(r, g, 0), 
        outline=rgb(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
    gradient2.create_rectangle(x*2, 0, x*2 + 2, 50, fill=rgb(r, g, 0), 
        outline=rgb(r, g, 0))

我相信这就是您所说的 "yellow checkpoints" 的意思。感谢您的挑战! :^)