Dùng phương thức after() gọi đệ quy hàm sau khoảng thời gian, dùng biến cờ condition để dừng.
Các bước
Tạo cửa sổ.
Hàm infinite_loop() in label, gọi lại mình bằng win.after(1000, infinite_loop) nếu condition=True.
Hàm start() set condition=True, stop() set False.
Tạo 2 Button gọi start/stop.
Khởi động loop bằng win.after(1000, infinite_loop).
Chạy mainloop.
Ví dụ
from tkinter import *
win = Tk()
win.geometry("700x350")
condition = True
def infinite_loop():
if condition:
Label(win, text="Infinite Loop!", font="Arial, 25").pack()
win.after(1000, infinite_loop)
def start():
global condition
condition = True
def stop():
global condition
condition = False
Button(win, text="Start the Loop", font="Arial, 12", command=start).pack()
Button(win, text="Stop the Loop", font="Arial, 12", command=stop).pack()
win.after(1000, infinite_loop)
win.mainloop()
Kết quả
Click "Start the Loop" → in "Infinite Loop!" mỗi giây. Click "Stop the Loop" → dừng.
