【发布时间】:2018-07-02 16:11:17
【问题描述】:
我正在使用 Tkinter 设计一个简单的计时器,该计时器在经过一定时间后会改变颜色。我有一个运行良好的基本计时器程序,但现在我想修改它,以便背景改变颜色。
我有 if 语句在适当的时间间隔触发,然后更改分配给背景颜色的类属性,但我无法更新标签颜色。
我了解“makeWidgets”功能只运行一次,并且相信这可能是我的问题的根源。我已经尝试将这个功能分解到主程序中,但效果好坏参半。我能够让计时器工作,但仍然无法改变颜色。我也尝试过编写颜色更改函数,但没有任何成功。我对 python、tkinter 和 full-disclosure 缺乏经验,我没有设计大部分基本计时器程序。
我非常感谢任何有关如何使其正常工作的指导/建议。我觉得我要么很接近,要么需要完全重新工作。希望是前者。
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()
【问题讨论】:
标签: python-3.x tkinter timer