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

วิธีหยุดลูปด้วยปุ่ม Stop ใน Tkinter


พิจารณากรณีที่รันกระบวนการในลูปและต้องการหยุดลูปเมื่อกดปุ่ม ในภาษาโปรแกรมทั่วไป ใช้คำสั่ง break เพื่อหยุดลูป while แต่ใน Tkinter แทน while loop เราใช้ after() เพื่อรันฟังก์ชันที่กำหนดในลูป เพื่อหยุดลูปต่อเนื่อง ให้ใช้ตัวแปร Boolean สากล (global) ที่สามารถอัปเดตเพื่อเปลี่ยนสถานะการทำงานของลูป

สำหรับตัวอย่างนี้:

  • สร้างตัวแปรสากลทำหน้าที่เหมือน flag ในลูป
  • กำหนดปุ่ม 2 ปุ่ม: Start และ Stop เพื่อเริ่มและหยุดการทำงาน
  • กำหนดฟังก์ชัน 2 ฟังก์ชัน: 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 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()

ผลลัพธ์

รันโค้ดเพื่อทดสอบลูปภายใต้เงื่อนไข

วิธีหยุดลูปด้วยปุ่ม Stop ใน Tkinter

หากรันโค้ดและกดปุ่ม Start จะพิมพ์ข้อความ "Hello World" ในลูป ซึ่งหยุดได้โดยกดปุ่ม "Stop"

Hello World Hello World Hello World Hello World Hello World Process finished with exit code 0