Tkinter でタイマーを使用する方法
Jinku Hu
2023年1月3日
2019年12月8日
Tkinter
Tkinter Timer

Tkinter root
ウィンドウは専用の方法 after
を持っています。この方法は所定の時間後に関数を呼び出します。
after(ms, func)
ms
は時間間隔、単位は ms
、
func
呼び出された関数名です。
try:
import Tkinter as tk
except:
import tkinter as tk
import time
class Clock():
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(text="", font=('Helvetica', 48), fg='red')
self.label.pack()
self.update_clock()
self.root.mainloop()
def update_clock(self):
now = time.strftime("%H:%M:%S")
self.label.configure(text=now)
self.root.after(1000, self.update_clock)
app=Clock()
self.root.after(1000, self.update_clock)
は、1000 ms
の後にその関数自体を呼び出しますので、upldate‗clock()
関数は 1000 ms
間隔で一回実行し、Tkinter ラベルに現在の時間を表示します。
注意
after
は、メソッドに設定された時間が非常に正確に関数を呼び出すことが保証されていません。アプリケーションが忙しい場合、Tkinter はシングルスレッドの場合、この遅延時間が延長される可能性がありますので、注意してください。Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn