Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo đồng hồ bấm giờ (Stopwatch) bằng Python Tkinter


Đồng hồ bấm giờ đo khoảng thời gian giữa 2 sự kiện (giây đến phút). Dùng trong thể thao, công nghiệp. Python tạo stopwatch bằng tkinter.

GUI có nút Start, Stop, Reset. Thành phần chính: label.after() của tkinter.

label.after(parent, ms, function=None)
parent: widget object
ms: thời gian miligiây
function: callback

Chương trình dùng after() làm trung tâm, thiết kế widget hiển thị stopwatch.

Ví dụ

import tkinter as tink

count = -1
run = False

def var_name(mark):
    def value():
        if run:
            global count
            if count == -1:
                show = "Starting"
            else:
                show = str(count)
            mark['text'] = show
            mark.after(1000, value)
            count += 1
    value()

def Start(mark):
    global run
    run = True
    var_name(mark)
    start['state'] = 'disabled'
    stop['state'] = 'normal'
    reset['state'] = 'normal'

def Stop():
    global run
    start['state'] = 'normal'
    stop['state'] = 'disabled'
    reset['state'] = 'normal'
    run = False

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()

Hình ảnh 4 trạng thái: Khởi động, Đang chạy, Dừng, Reset.

Tạo đồng hồ bấm giờ (Stopwatch) bằng Python Tkinter

Tạo đồng hồ bấm giờ (Stopwatch) bằng Python Tkinter

Tạo đồng hồ bấm giờ (Stopwatch) bằng Python Tkinter

Tạo đồng hồ bấm giờ (Stopwatch) bằng Python Tkinter