Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng Thread (luồng) trong Tkinter Python?

Với Tkinter, có thể gọi nhiều hàm cùng lúc nhờ Threading – thực thi bất đồng bộ.

Để dùng thread: import module threading, kế thừa class Thread, ghi đè phương thức run() chứa logic. Tkinter cung cấp Thread() để thực hiện đa luồng.

Ví dụ: tạo thread sleep 5 giây song song với giao diện.

Cần import time và threading.

Ví dụ

# Import thư viện
from tkinter import *
import time
import threading

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

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)

# Tạo button chạy thread
b1 = Button(win, text="Start", command=threading.Thread(target=thread_fun).start())
b1.pack(pady=20)

win.mainloop()

Kết quả

Chạy code tạo button và thread cập nhật label sau 5 giây.

Cách dùng Thread (luồng) trong Tkinter Python?

Sau 5 giây, thread cập nhật label.

Cách dùng Thread (luồng) trong Tkinter Python?