Tkinter ใช้กันอย่างแพร่หลายในการสร้างและพัฒนาแอปพลิเคชันและเกมแบบ GUI Tkinter มีหน้าต่างหรือเฟรมที่เรารันโปรแกรมและฟังก์ชันพร้อมกับแอตทริบิวต์อื่นๆ
สมมติว่าเรากำลังทำงานกับแอปพลิเคชันเฉพาะ และเราต้องการเขียนการเปลี่ยนแปลงในโค้ดขณะที่แอปพลิเคชันกำลังรัน Tkinter มี Callback Method ที่สามารถใช้รันหน้าต่างขณะวนลูปผ่านมัน เราสามารถรันหน้าต่างต่อเนื่องได้โดยใช้เมธอด after(duration, task) ซึ่งจะรันการเปลี่ยนแปลงหลังจาก Duration
ในตัวอย่างนี้ เราจะสร้างหน้าต่างที่พิมพ์ตัวเลขในช่วง (0 ถึง 9) ขณะที่รัน Main Window หรือ Frame
ตัวอย่าง
# Import the required libraries
from tkinter import *
from tkinter import messagebox
# Create an instance of tkinter frame or window
win = Tk()
# Set the geometry
win.geometry("700x200")
# Define the function for button
def some_task():
for i in range(10):
print(i)
# Recursively call the function
win.after(2000, some_task)
# Keep Running the window
win.after(2000, some_task)
win.mainloop()
ผลลัพธ์
การรันโค้ดข้างต้นจะพิมพ์ตัวเลขในช่วง (0 ถึง 9) บน Console ตลอดเวลา และพร้อมกับนั้น แสดง Main Window
0
1
2
3
4
5
6
7
8
9
.....
