在Tkinter中绘制一个范围从红色到绿色的比例

时间:2015-02-10 16:35:37

标签: python-3.x colors tkinter gradient

我想绘制一个从红色到绿色的刻度。我设法做了一个范围从绿色到黄色的比例。现在我有两种可能的解决方案:

  • 绘制2个渐变:一个从红色到黄色,一个从黄色到绿色。然后我可以链接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()

1 个答案:

答案 0 :(得分:1)

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

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

我相信你的意思是黄色检查站&#34;。感谢您的挑战! :^)