如何在 Tkinter Python 中使用執行緒?
使用 Tkinter,我們可以使用執行緒一次呼叫多個函式。它提供了一個應用程式中某些函式的非同步執行。
為了使用 Python 中的執行緒,我們可以匯入一個名為threading的模組,並對其Thread類進行子類化。在我們的新類中,我們需要重寫Run方法,並在其中執行我們的邏輯。
所以,基本上有了執行緒,我們可以一次做多項工作。要在我們的應用程式中實現執行緒,Tkinter 提供了Thread()函式。
讓我們舉個例子,建立一個將休眠一段時間然後並行執行另一函式的執行緒。
對於這個示例,我們將匯入在 Tkinter 庫中定義的Time 模組和threading 模組。
示例
#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()
輸出
執行以上程式碼將建立一個按鈕和一個作用於標籤的執行緒。
5 秒後,執行緒將自動暫停。
廣告