用 Python 创建秒表
秒表用于测量两个事件之间的时间间隔,通常以秒到分钟为单位。它在体育或测量工业环境中热流、电流等方面有着广泛的用途。Python 可通过使用其 Tkinter 库来创建秒表。
此库将具有 GUI 功能,以创建显示 启动、停止和重置 选项的秒表。该程序的关键组件是使用 Tkinter 的lable.after() 模块。
label.after(parent, ms, function = None) where parent: The object of the widget which is using this function. ms: Time in miliseconds. function: Call back function
在以下程序中,我们使用此方法作为程序的关键组件,并设计了一个在秒表中显示 GUI 功能的小部件。
示例
import tkinter as tink count = -1 run = False def var_name(mark): def value(): if run: global count # Just beore starting if count == -1: show = "Starting" else: show = str(count) mark['text'] = show #Increment the count after #every 1 second mark.after(1000, value) count += 1 value() # While Running def Start(mark): global run run = True var_name(mark) start['state'] = 'disabled' stop['state'] = 'normal' reset['state'] = 'normal' # While stopped def Stop(): global run start['state'] = 'normal' stop['state'] = 'disabled' reset['state'] = 'normal' run = False # For Reset def Reset(label): global count count = -1 if run == False: reset['state'] = 'disabled' mark['text'] = 'Welcome' else: mark['text'] = 'Start' base = tink.Tk() base.title("PYTHON STOPWATCH") base.minsize(width=300, height=200) mark = tink.Label(base, text="Welcome", fg="blue", font="Times 25 bold",bg="white") mark.pack() start = tink.Button(base, text='Start',width=25, command=lambda: Start(mark)) stop = tink.Button(base, text='Stop', width=25, state='disabled', command=Stop) reset = tink.Button(base, text='Reset',width=25, state='disabled', command=lambda: Reset(mark)) start.pack() stop.pack() reset.pack() base.mainloop()
以下图像显示了运行秒表时的三种不同场景。
启动秒表
运行的秒表
停止秒表
重置秒表
广告