ด้วย Tkinter เราสามารถเรียกใช้ฟังก์ชันหลายฟังก์ชันพร้อมกันได้โดยใช้ Threading ซึ่งให้การทำงานแบบ Asynchronous ของบางฟังก์ชันในแอปพลิเคชัน
เพื่อใช้ Thread ใน Python เราสามารถ import โมดูล threading และสร้าง subclass ของคลาส Thread ภายในคลาสใหม่ เราต้อง override เมธอด Run และวางตรรกะของเราไว้ที่นั่น
สรุปคือ ด้วย Threading เราสามารถทำงานหลายอย่างพร้อมกันได้ Tkinter มีฟังก์ชัน Thread() สำหรับการทำ Threading
ลองสร้างตัวอย่าง Thread ที่จะ sleep เป็นเวลาสักพักแล้วค่อยทำงานฟังก์ชันอื่นแบบขนาน
สำหรับตัวอย่างนี้ เราจะ import Time module และ threading module ที่อยู่ในไลบรารี Tkinter
ตัวอย่าง
# Import all the necessary libraries
from tkinter import *
import time
import threading
# Define the tkinter instance
win = Tk()
# Define the size of the tkinter frame
win.geometry("700x400")
# Define the function to start the thread
def thread_fun():
label.config(text="You can Click the button or Wait")
time.sleep(5)
label.config(text="5 seconds Up!")
label = Label(win)
label.pack(pady=20)
# Create button
b1 = Button(win, text="Start", command=threading.Thread(target=thread_fun).start())
b1.pack(pady=20)
win.mainloop()
ผลลัพธ์
การรันโค้ดข้างต้นจะสร้างปุ่มและ Thread ที่ทำงานบน Label

หลังจาก 5 วินาที Thread จะหยุดทำงานอัตโนมัติ
