Python自动秒表

时间:2018-10-29 00:18:46

标签: python python-3.x tkinter stopwatch

我有以下用于stop watch的代码。运行时,您会看到带有开始按钮的秒表。 我还有另一个用于计算长方程的代码,需要花费很长时间才能解决。如何将代码放在以下代码中:当我运行代码时,秒表将自动开始计数,当代码完成其计算后,秒表将停止计数。

import tkinter
import time

class StopWatch(tkinter.Frame):

@classmethod
def main(cls):
    tkinter.NoDefaultRoot()
    root = tkinter.Tk()
    root.title('Stop Watch')
    root.resizable(True, False)
    root.grid_columnconfigure(0, weight=1)
    padding = dict(padx=5, pady=5)
    widget = StopWatch(root, **padding)
    widget.grid(sticky=tkinter.NSEW, **padding)
    root.mainloop()

def __init__(self, master=None, cnf={}, **kw):
    padding = dict(padx=kw.pop('padx', 5), pady=kw.pop('pady', 5))
    super().__init__(master, cnf, **kw)
    self.grid_columnconfigure(1, weight=1)
    self.grid_rowconfigure(1, weight=1)
    self.__total = 0
    self.__label = tkinter.Label(self, text='Total Time:')
    self.__time = tkinter.StringVar(self, '0.000000')
    self.__display = tkinter.Label(self, textvariable=self.__time)
    self.__button = tkinter.Button(self, text='Start', command=self.__click)
    self.__label.grid(row=0, column=0, sticky=tkinter.E, **padding)
    self.__display.grid(row=0, column=1, sticky=tkinter.EW, **padding)
    self.__button.grid(row=1, column=0, columnspan=2,
                       sticky=tkinter.NSEW, **padding)

def __click(self):
    if self.__button['text'] == 'Start':
        self.__button['text'] = 'Stop'
        self.__start = time.clock()
        self.__counter = self.after_idle(self.__update)
    else:
        self.__button['text'] = 'Start'
        self.after_cancel(self.__counter)

def __update(self):
    now = time.clock()
    diff = now - self.__start
    self.__start = now
    self.__total += diff
    self.__time.set('{:.6f}'.format(self.__total))
    self.__counter = self.after_idle(self.__update)

if __name__ == '__main__':
    StopWatch.main()

非常感谢

0 个答案:

没有答案