พิจารณากรณีของการรันกระบวนการในลูปและเราต้องการหยุดการวนซ้ำทุกครั้งที่มีการคลิกปุ่ม โดยทั่วไปในภาษาโปรแกรม การหยุดต่อเนื่อง ในขณะที่ loop เราใช้ break คำแถลง. อย่างไรก็ตาม ใน Tkinter แทนที่ ในขณะที่ วนซ้ำ เราใช้ after() เพื่อเรียกใช้ฟังก์ชันที่กำหนดไว้ในลูป หากต้องการทำลายการวนซ้ำต่อเนื่อง ให้ใช้ตัวแปรบูลีนร่วมซึ่งสามารถอัปเดตเพื่อเปลี่ยนสถานะการทำงานของลูปได้
สำหรับตัวอย่างที่กำหนด
-
สร้างตัวแปรส่วนกลางที่ทำงานคล้ายกับ แฟล็ก เป็นวงวน
-
กำหนดสองปุ่ม เริ่ม และ หยุด , เพื่อเริ่มและหยุดการดำเนินการ
-
กำหนดสองฟังก์ชัน on_start() และ on_stop() , เพื่อส่งการอัปเดตในลูป
ตัวอย่าง
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
running = True
# Define a function to print the text in a loop
def print_text():
if running:
print("Hello World")
win.after(1000, print_text)
# Define a function to start the loop
def on_start():
global running
running = True
# Define a function to stop the loop
def on_stop():
global running
running = False
canvas = Canvas(win, bg="skyblue3", width=600, height=60)
canvas.create_text(150, 10, text="Click the Start/Stop to execute the Code", font=('', 13))
canvas.pack()
# Add a Button to start/stop the loop
start = ttk.Button(win, text="Start", command=on_start)
start.pack(padx=10)
stop = ttk.Button(win, text="Stop", command=on_stop)
stop.pack(padx=10)
# Run a function to print text in window
win.after(1000, print_text)
win.mainloop() ผลลัพธ์
รันโค้ดด้านบนเพื่อทดสอบลูปสำหรับเงื่อนไขบางอย่าง

หากเราจะเรียกใช้โค้ดด้านบนและคลิกปุ่มเริ่ม ระบบจะพิมพ์ข้อความ "Hello World" ในลูปที่สามารถหยุดได้ด้วยการคลิกปุ่ม "หยุด"
Hello World Hello World Hello World Hello World Hello World Process finished with exit code 0