Python 如何为变量指定秒表时间单位
这段免费提供的代码是一个秒表GUI应用程序。按下停止按钮后,如何将分钟、秒和毫秒分配给单个变量m、s、ms 首先,我在Stop函数中尝试了Python 如何为变量指定秒表时间单位,python,tkinter,Python,Tkinter,这段免费提供的代码是一个秒表GUI应用程序。按下停止按钮后,如何将分钟、秒和毫秒分配给单个变量m、s、ms 首先,我在Stop函数中尝试了m=self.timestr.get() from Tkinter import * import time class StopWatch(Frame): """ Implements a stop watch frame widget. """
m=self.timestr.get()
from Tkinter import *
import time
class StopWatch(Frame):
""" 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()
def makeWidgets(self):
""" Make the time label. """
l = Label(self, textvariable=self.timestr)
self._setTime(self._elapsedtime)
l.pack(fill=X, expand=NO, 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):
""" 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))
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)
def main():
root = Tk()
sw = StopWatch(root)
sw.pack(side=TOP)
Button(root, text='Start', command=sw.Start).pack(side=LEFT)
Button(root, text='Stop', command=sw.Stop).pack(side=LEFT)
Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
Button(root, text='Quit', command=root.quit).pack(side=LEFT)
root.mainloop()
if __name__ == '__main__':
main()
在\u setTimer
中创建
minutes = int(elap/60)
seconds = int(elap - minutes*60.0)
hseconds = int((elap - minutes*60.0 - seconds)*100)
因此,使用self.minutes
,self.seconds
,self.hseconds
,您就不必使用self.timestr.get()
您只需在计时器运行时保存计算的分、秒和小时,以后就不必进行转换。调试我的程序后,分钟、秒和毫秒的值之所以为0,是因为在我调用秒表的主程序中,我一直在覆盖秒表小部件。白痴!我不明白这个问题。它已经计算了小时、分钟和秒。这只是一个基本的数学方程式。hours=int(elap/3600)minutes=int(elap/60-hours*60)seconds=int(elap-hours*3600-minutes*60.0)