我正在设计一个使用Tkinter的简单计时器,该计时器会在经过一定时间后改变颜色。我有一个基本的计时器程序,可以很好地工作,但是现在我想对其进行修改,以使背景改变颜色。
我有if语句,它们在适当的时间间隔触发,然后更改分配给背景颜色的class属性,但是我无法更新标签颜色。
我了解“ makeWidgets”功能仅运行一次,并认为这可能是我问题的根源。我已经尝试过将此功能分解到主程序中,但取得了不同的成功。我能够使计时器工作,但仍然无法改变颜色。我也尝试编写颜色更改函数,但没有成功。我对python,tkinter和全公开没有经验,我没有设计大量的基本计时器程序。
我真的很感激任何有关如何使它工作的方向/建议。我觉得我要么很亲密,要么需要彻底重做。希望是这样。
from tkinter import *
import time
class StopWatch(Frame):
global mincount
""" Implements a stop watch frame widget. """
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
self.start = 0.0
self.elapsedtime = 0.0
self.running = 0
self.timestr = StringVar()
self.makeWidgets()
self.color = 'green'
def makeWidgets(self): #this function only run once at setup
""" Make the time label. """
self.color='green' #this works
l = Label(self, textvariable=self.timestr, bg=self.color, font=("Helvetica",300), width=12, height=2)
self.setTime(self.elapsedtime)
l.pack(fill=X, expand=YES, pady=2, padx=2)
def update(self):
""" Update the label with elapsed time. """
self.elapsedtime = time.time() - self.start
self.setTime(self.elapsedtime)
self.timer = self.after(50, self.update)
def setTime(self, elap,):
global mincount
""" Set the time string to Minutes:Seconds:Hundreths """
minutes = int(elap/60)
seconds = int(elap - minutes*60.0)
hseconds = int((elap - minutes*60.0 - seconds)*100)
self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))
mincount = int(elap)
if mincount>=3:
print("yellow")
self.color='yellow' #has no effect
l.config(bg='yellow') #not in scope
#CHANGE COLOR TO YELLOW - call fx?
if mincount>=5:
print("red")
#CHANGE COLOR TO RED
def Start(self):
""" Start the stopwatch, ignore if running. """
if not self.running:
self.start = time.time() - self.elapsedtime
self.update()
self.running = 1
def Stop(self):
""" Stop the stopwatch, ignore if stopped. """
if self.running:
self.after_cancel(self.timer)
self.elapsedtime = time.time() - self.start
self.setTime(self.elapsedtime)
self.running = 0
def Reset(self):
""" Reset the stopwatch. """
self.start = time.time()
self.elapsedtime = 0.0
self.setTime(self.elapsedtime)
self.color='green'
def main():
root = Tk()
sw = StopWatch(root)
sw.pack(side=TOP)
Button(root, text='Start', command=sw.Start).pack(side=BOTTOM, fill=BOTH)
Button(root, text='Stop', command=sw.Stop).pack(side=BOTTOM, fill=BOTH)
Button(root, text='Reset', command=sw.Reset).pack(side=BOTTOM, fill=BOTH)
Button(root, text='Quit', command=root.quit).pack(side=BOTTOM, fill=BOTH)
current=sw.timestr
root.mainloop()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
您不能在l
函数中使用setTime
:l
是makeWidgets
中的局部变量
它不能在setTime
中使用。要解决此问题,您必须使l
成为makeWidgets
中类的变量部分:例如self.label = ...
。然后在self.label
中使用新变量setTime
:self.label.config("bg"="yellow")
如果您的if语句if mincount>=3:
可以改善某些情况,因为如果是,则更改bg,然后再检查if mincount>=5
。您应该这样做:
if mincount>=5:
...
elif mincount >=3:
...