1 回答

TA貢獻1811條經驗 獲得超4個贊
所以我這樣做了,但我不知道它是否適合你,或者這是否是一個很好的方法,但它可以像評論中所述那樣保護你,它的好處是.after你的函數do_stuff只在需要時被調用.
import tkinter as tk
import time
import threading
def get_data():
? ? time.sleep(3)
? ? print('sleeped 3')
? ? _check.set(1)
def do_stuff():
? ? try:
? ? ? ? root.configure(bg='#'+str(_var.get()))
? ? ? ? _var.set(_var.get()+101010)
? ? except:
? ? ? ? _var.set(101010)
root = tk.Tk()
_check = tk.IntVar(value=0)
_var = tk.IntVar(value=101010)
def callback(event=None, *args):
? ? t1 = threading.Thread(target=get_data)
? ? t1.start()
? ??
? ? do_stuff()
? ??
_check.trace_add('write', callback) #kepp track of that variable and trigger callback if changed
callback() # start the loop
root.mainloop()
一些研究:
interpreter 僅在創建它的線程中有效,所有 Tk 活動也必須在該線程中發生。這意味著必須在創建解釋器的線程中調用主循環。可以從其他線程調用命令;_tkinter 將為解釋器線程排隊一個事件,然后解釋器線程將執行命令并傳回結果。
#l1493?var_invoke
?The?current?thread?is?not?the?interpreter?thread.??Marshal ???????the?call?to?the?interpreter?thread,?then?wait?for ???????completion.?*/????if?(!WaitForMainloop(self))?? ?????????????return?NULL;
在 python 線程中使用 intvar-doublevar 是否安全
當您設置一個變量時,它會在與該變量關聯的主控件上調用 globalsetvar 方法。_tk.globalsetvar 方法在 C 中實現,并在內部調用 var_invoke,后者在內部調用 WaitForMainLoop,它將嘗試安排命令在主線程中執行,如我上面引用的 _tkinter 源中所述。
? ? ?Start
? ? ? ?|
? ? ? ?|<----------------------------------------------------------+
? ? ? ?v? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^
? ?Do I have? ? No[*]? Calculate how? ? ? ? ? ? Sleep for at? ? ? ?|
? ?work to do?? -----> long I may sleep? -----> most that much --->|
? ? ? ?|? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? time? ? ? ? ? ? ? ?|
? ? ? ?| Yes? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|
? ? ? ?|? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|
? ? ? ?v? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|
? ?Do one callback? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|
? ? ? ?|? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|
? ? ? ?+-----------------------------------------------------------+
常識
來自錯誤追蹤器:
Tkinter 和線程。
如果你想同時使用 tkinter 和線程,最安全的方法是在主線程中進行所有 tkinter 調用。如果工作線程生成 tkinter 調用所需的數據,請使用 queue.Queue 將數據發送到主線程。為了徹底關閉,添加一個方法來等待線程停止并在按下窗口關閉按鈕 [X] 時調用它。
效果機器人
只需在主線程中運行所有 UI 代碼,讓編寫器寫入一個 Queue 對象;例如
結論
你做事的方式和我做事的方式似乎很理想,但它們似乎一點也沒錯。這取決于需要什么。
添加回答
舉報