2

我尝试使用非常幼稚的方法(绘制线条序列)编写自己的简单函数来绘制渐变(仅灰色),但实际上代表渐变的矩形的颜色始终是统一的颜色(我认为它是循环中的最新颜色)。你能解释一下为什么吗?这是代码:

import Tkinter

class testGUI:
    def __init__( self, root ):
        C = Tkinter.Canvas( root, bg = "blue", height = 250, width = 300 )
        self.drawGradient( C, 10, 10, 100, 50 )
        C.pack()

    def drawGradient( self, canvas, x, y, w, h ):
        for offset in range( 0, w ):
            gradColor = '#%02x%02x%02x' % ( x * 10, x * 10, x * 10 )
            canvas.create_line( x + offset, y, x + offset, y + h, fill = gradColor )

root = Tkinter.Tk()
app = testGUI( root )
root.mainloop()
4

1 回答 1

3

颜色始终相同,因为您使用的颜色不依赖于循环的迭代:

for offset in ...
    gradColor = '#%02x%02x%02x' % ( x * 10, x * 10, x * 10 )

要使其改变, 的值gradColor必须取决于 的值offset,例如:

def drawGradient(self, canvas, x, y, w, h):
    factor = 255./w
    for offset in range(0, w):
        gradColor = '#%02x%02x%02x' % (offset*factor, offset*factor, offset*factor)
        canvas.create_line(x + offset, y, x + offset, y + h, fill=gradColor)
于 2013-05-27T20:43:40.507 回答