【问题标题】:Crossfading between label colors over time in tkinter?在tkinter中随着时间的推移标签颜色之间的交叉淡入淡出?
【发布时间】:2012-05-16 22:13:41
【问题描述】:

我可以在 Tkinter 中为标签的背景在两种颜色之间实现淡入淡出的方法是什么? 我希望我的计时器标签的颜色在倒计时时改变。这些是我目前正在使用的 sn-ps,(以澄清我在做什么)。

…

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 )

…

【问题讨论】:

  • 你对这个问题有什么不明白的地方?不知道如何更改标签的背景颜色,或者不知道如何创建颜色范围,或者还有其他不明白的地方?
  • @Bryan 我不明白如何从数学的角度进行自身的褪色,并从那里创建一个可用的函数,用于基于计时器在任何两种颜色之间进行褪色。抱歉我的问题不清楚。

标签: python colors tkinter


【解决方案1】:

这是我编写的一段小代码,用于创建带有渐变的颜色条。我不知道它是否对你有用,但是......它有效......

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

这在课堂上会更简洁,但希望你能明白。

【讨论】:

  • 这对其他原因很有用,但不是我想要的。随着我的计数器倒计时,我想随着时间的推移更改画布背景颜色。我改写了我的问题,希望能让我想做的事情更清楚。
  • @RyanHasse 这也很容易。只需使用 cinterp 函数,然后调用它来更新您的标签/画布/在 after 调用中重新注册的任何内容。我现在没有时间发布真正的解决方案,但如果您还没有弄清楚,我可以在早上发布。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多