标签颜色之间的交叉渐变随着时间的推移在tkinter中?

问题描述 投票:0回答:1

对于Tkinter中标签的背景,我可以在两种颜色之间实现淡出时间的方式是什么?我希望我的计时器标签的颜色随着倒计时而改变。这些是我目前正在处理的片段,(澄清我正在做的事情)。

…

labelcolor = "#%02x%02x%02x" % (0, 0, 0)

…

def pomodoro(self, remaining = None):
    self.button.configure(state=tk.DISABLED)
    self.labelcolor = "#%02x%02x%02x" % (200, 32, 32)
    self.label.configure(bg = self.labelcolor)
    if remaining is not None:
        self.remaining = remaining

    if self.remaining <= 0:
        self.label.configure(text="Time's up!")
        self.breakcommand
    else:
        self.label.configure(text= time.strftime('%M:%S', time.gmtime(self.remaining))) #Integer to 'Minutes' and 'Seconds'
        self.remaining = self.remaining - 1
        self.after(1000, self.pomodoro)

…

self.label = tk.Label(self, text="Pick One", width=12, font="Helvetica 32", fg = "white", bg = self.labelcolor )

…
python colors tkinter
1个回答
4
投票

这是一个小代码,我一起攻击以创建一个带渐变的颜色条。我不知道它对你有用,但是......它有效......

import Tkinter as tk

def cinterp(x1,x2,x,c1,c2):
    """
    interpolate two colors.  c1 and c2 are 3-tuples of rgb values -- 
    e.g. (0,0,255)

    x1,x2 and x are used to determine the interpolation constants.
    """
    s1=float(x-x1)/(x2-x1)
    s2=1.-s1
    return [max(0, min(255, int(s1 * i + s2 * j))) for i, j in zip(c1, c2)]

root=tk.Tk()
cvs=tk.Canvas(root,width=100,height=50)
cvs.grid(row=0,column=0)
width=int(cvs['width']) 
height=int(cvs['height'])
for i in range(width):
   fill=cinterp(0,width,i,(255,0,0),(255,255,255))
   fs="#%02x%02x%02x"%(fill[0],fill[1],fill[2])
   cvs.create_rectangle(i,1,i+1,height,fill=fs,width=0)

root.mainloop()

当然,您可能希望在矩形上保留一个句柄,以便稍后更改颜色,您也可以更有效地执行此操作,但这可能是一个很好的起点。

编辑

import Tkinter as tk

def cinterp(x1,x2,x,c1,c2):
    s1=float(x-x1)/(x2-x1)
    s2=1.-s1
    return [max(0, min(255, int(s1 * i + s2 * j))) for i, j in zip(c1, c2)]

root=tk.Tk()
cvs=tk.Label(root,text="Hello")
c2=(255,0,0)
c1=(255,255,255)
def updateCVS(dt,timeleft,deltat):
    timeleft=timeleft-dt
    fill=cinterp(0,deltat,deltat-timeleft,c1,c2)
    fs="#%02x%02x%02x"%(fill[0],fill[1],fill[2])
    cvs.configure(bg=fs)
    if(timeleft>0):
        timeleft=timeleft-dt
        cvs.after(int(dt*1000),updateCVS,dt,timeleft,deltat)

cvs.grid(row=0,column=0)
b=tk.Button(root,text="push me",command=lambda : updateCVS(.2,5,5))
b.grid(row=1,column=0)

root.mainloop()

在课堂上这会更加清洁,但希望你能得到这个想法。

© www.soinside.com 2019 - 2024. All rights reserved.