我有一個python GUI程序需要執行相同的任務,但有幾個線程。問題是我調用線程,但它們不會並行執行,而是按順序執行。第一個執行,結束,然後第二個,等等。我希望他們獨立開始。Python GUI保持凍結,等待線程代碼完成運行
的主要元件包括:
1.菜單(視圖)
2. ProcesStarter(控制器)
3.過程(控制器)
的菜單是你點擊 「開始」在ProcesStarter處調用功能的按鈕。
的ProcesStarter創建過程和線程的物體,並且開始所有線程在一個for循環。
菜單:
class VotingFrame(BaseFrame):
def create_widgets(self):
self.start_process = tk.Button(root, text="Start Process", command=lambda: self.start_process())
self.start_process.grid(row=3,column=0, sticky=tk.W)
def start_process(self):
procesor = XProcesStarter()
procesor_thread = Thread(target=procesor.start_process())
procesor_thread.start()
ProcesStarter:
class XProcesStarter:
def start_process(self):
print "starting new process..."
# thread count
thread_count = self.get_thread_count()
# initialize Process objects with data, and start threads
for i in range(thread_count):
vote_process = XProcess(self.get_proxy_list(), self.get_url())
t = Thread(target=vote_process.start_process())
t.start()
過程:
class XProcess():
def __init__(self, proxy_list, url, browser_show=False):
# init code
def start_process(self):
# code for process
當我按下GUI按鈕F或「啓動過程」,gui被鎖定,直到兩個線程完成執行。 這個想法是,線程應該在後臺工作,並行工作。
不完全精確,'螺紋(目標=無)。開始()'是完全有效的,更何況在物體上的方法是可調用的,所以初始化它然後在線程中運行該方法沒有任何問題。 –
謝謝!我今天學到了東西! (我也會編輯我的答案) –
已將代碼更改爲此,並且按預期工作! – nullwriter