Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

สร้างปุ่ม Stop หยุด Infinite Loop ใน Tkinter

ใช้ตัวแปร global flag (run = True/False) ควบคุมลูป recursive ที่เรียกด้วย after()

ตัวอย่างโค้ด

from tkinter import *

win = Tk()
win.geometry("700x350")

run = True

def print_hello():
    if run:
        Label(win, text="Hello World", font=('Helvetica 10 bold')).pack()
        win.after(1000, print_hello)

def start():
    global run
    run = True

def stop():
    global run
    run = False

Button(win, text="Start", command=start).pack(padx=10)
Button(win, text="Stop", command=stop).pack(padx=15)

win.after(1000, print_hello)
win.mainloop()

ผลลัพธ์

กด Start เริ่มลูป กด Stop หยุดลูปทันที

สร้างปุ่ม Stop หยุด Infinite Loop ใน Tkinter