tkinter で「ストップウォッチ」アプリを作成
下記サイトの写経です。 daeudaeu.com
import tkinter import time # https://daeudaeu.com/stopwatch/ INTERVAL = 5 start_time = 0 start_flg = False after_id = 0 app = tkinter.Tk() app.title("stop watch") app.geometry("250x200") def update_time(): global start_time global app, label global after_id after_id = app.after(INTERVAL, update_time) now_time = time.time() elapsed_time = now_time - start_time elapsed_time_str = "{:.2f}".format(elapsed_time) label.config(text=elapsed_time_str) def start(): global app global start_time global start_flg global after_id if not start_flg: start_flg = True start_time = time.time() after_id = app.after(INTERVAL, update_time) def stop(): global start_flg global after_id if start_flg: app.after_cancel(after_id) start_flg = False def reset(): if not start_flg: label.config(text="0.00") # 時刻表示 label = tkinter.Label( app, text="0.00", width=6, font=("", 50, "bold"), ) label.pack(pady=5) #スタートボタン start_button = tkinter.Button( app, text="START", command=start ) start_button.pack(pady=5) #ストップボタン start_button = tkinter.Button( app, text="STOP", command=stop ) start_button.pack(pady=5) #リセットボタン start_button = tkinter.Button( app, text="RESET", command=reset ) start_button.pack(pady=5) app.mainloop()