python tkinter 实现简易秒表计时器

import time
import tkinter

root = tkinter.Tk()
root.title('秒表计数器')
root.geometry("400x200+300+200")
frame1 = tkinter.Frame(root) #框架
frame1.pack()
timestr = tkinter.StringVar()   #创建可变数据类型
timestr.set('0:0')   #只能数值不能等于号

running = False    #计时器工作状态
starttime = 0      #开始计时时间
elapsedtime = 0.0    #计时器统计到的时间
timer = None

def update():
    global elapsedtime
    global timestr
    global timer
    elapsedtime = time.time() - starttime
    timestr.set(elapsedtime)
    timer = root.after(50, update)

def Start():
    global running  #全局变量
    global starttime
    if not running:
        starttime = time.time() - elapsedtime
        running = True
        update()
        pass

def Stop():
    global running
    global timer
    if running:
        root.after_cancel(timer)
        elapsedtime = time.time() - starttime
        timestr.set(elapsedtime)
        running = False
        pass

def Reset():
    global elapsedtime
    global timestr
    global starttime
    elapsedtime = 0.0
    starttime = time.time()
    timestr.set(elapsedtime)



tkinter.Label(frame1, textvariable=timestr).pack()  # 文本变量
tkinter.Button(frame1, text='开始', command=Start).pack(side=tkinter.LEFT)
tkinter.Button(frame1, text='停止', command=Stop).pack(side=tkinter.LEFT)
tkinter.Button(frame1, text='重置', command=Reset).pack(side=tkinter.LEFT)
tkinter.Button(frame1, text='退出', command=quit).pack(side=tkinter.LEFT)


root.mainloop()

下面是代码效果:

        python tkinter 实现简易秒表计时器_第1张图片

 

你可能感兴趣的:(python tkinter 实现简易秒表计时器)