我創建了一個示例代碼,因為我的原件太大并且其中包含私人資訊(我自己的)。
從 Tkinter GUI 運行程式時,它會運行程式但由于 time.sleep() 阻止 GUI 更新而使 GUI 無回應。
我試圖避免使用計時器,因為它會在一段時間后觸發不同的功能,而不是簡單地暫停功能然后繼續相同的功能。
是否有替代方案不會阻止 GUI,但仍會在函式內部添加延遲?
示例代碼:
from tkinter import *
import time
wn = Tk()
wn.geometry("400x300")
MyLabel = Label(wn, text="This is a Status Bar")
MyLabel.pack()
def MyFunction():
Value = 1
while Value < 10:
print("Do something")
time.sleep(1) **# - here blocks everything outside of the function**
MyLabel.config(text=Value)
# A lot more code is under here so I cannot use a timer that fires a new function
Value = 1
MyButton = Button(wn, text="Run Program", command=MyFunction)
MyButton.pack()
wn.mainloop()
編輯:非常感謝,您的回答很快而且很有幫助,我更改了代碼并在延遲后添加了“wn.mainloop()”,并將“time.sleep(1)”替換為 wn.after(100, wn.之后(10,MyLabel.config(文本=值))
這是最終代碼:
from tkinter import *
import time
wn = Tk()
wn.geometry("400x300")
MyLabel = Label(wn, text="This is a Status Bar")
MyLabel.pack()
def MyFunction():
Value = 0
while Value < 10:
print("Do something")
wn.after(10, MyLabel.config(text=Value))
Value = 1
wn.mainloop()
MyButton = Button(wn, text="Run Program", command=MyFunction)
MyButton.pack()
wn.mainloop()
uj5u.com熱心網友回復:
簡短的回答是,您可以wn.after()在一定時間后使用請求回呼。你就是這樣處理的。您以每秒一個的速度獲得一個計時器滴答,并且您有足夠的狀態資訊讓您進入下一個狀態,然后您回傳主回圈。
換句話說,計時器正是您解決此問題的方法。
uj5u.com熱心網友回復:
從根本上說,Tkinter 中的任何回呼函式都在主 GUI 執行緒中運行,因此 GUI 執行緒將阻塞直到函式退出。因此,您不能在函式內部添加延遲而不導致 GUI 執行緒延遲。
有兩種方法可以解決這個問題。一種是將您的函式重構為多個部分,以便它可以通過.after. 這樣做的好處是確保你的所有函式都在主執行緒中運行,因此你可以直接執行 GUI 操作。
另一種方法是在一個單獨的執行緒中運行你的函式,只要你的主回呼被執行,這個執行緒就會被啟動。這使您可以將所有邏輯保留在一個函式中,但它不能再直接執行 GUI 操作 - 相反,任何 GUI 操作都必須通過您從主執行緒管理的事件佇列。
uj5u.com熱心網友回復:
您可以在不阻止 tkinter 處理未決事件和更新的情況下進行組合after()和wait_variable()模擬:time.sleep()
def tk_sleep(delay):
v = wn.IntVar()
# update variable "delay" ms later
wn.after(delay, v.set, 0)
# wait for update of variable
wn.wait_variable(v)
tk_sleep()在你的 while 回圈中使用:
def MyFunction():
Value = 1
while Value < 10:
print("Do something")
tk_sleep(1000) # waits for one second
MyLabel.config(text=Value)
# A lot more code is under here so I cannot use a timer that fires a new function
Value = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425926.html
