我尝试使用非常天真的方法(绘制线条序列)来编写我自己的简单函数来绘制渐变(仅灰色),但是代表渐变的矩形的颜色通常是均匀的颜色(我认为)它是循环中的最新颜色)。你能解释一下原因吗?这是代码:
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()
答案 0 :(得分: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)