0
我有一個tkinter接口,帶有兩個按鈕以觸發我的應用程序的兩種模式以及顯示它處於哪種模式的標籤。單擊按鈕時,生成的函數被稱爲需要一段時間來執行並回來。這導致我的鼠標光標在旋轉,並且該按鈕基本上被「凍結」,直到該功能完成其執行,然後我可以單擊另一個按鈕。tkinter按鈕單擊以啓動線程以防止GUI凍結
我想要的行爲是,我單擊一個按鈕,它異步運行函數(新線程),並使按鈕再次可點擊。如果單擊另一個按鈕,則立即停止該第一個線程,並且新的函數/線程異步啓動。
我該如何去做到這一點?
def alert_mode(var):
print("Entering Alert Mode")
var.set("Current mode: Alert")
// do stuff that takes a while to return
def capture_mode(var):
print("Entering Capture Mode")
var.set("Current mode: Capture")
// do stuff that takes a while to return
root = tk.Tk()
root.geometry('400x400')
var = StringVar()
var.set("Current mode: Alert")
text = tk.Label(root, text="Current mode: Alert", textvariable=var, fg="blue", font=("Arial", 18))
text.pack(pady=8)
b = tk.Button(root, text="Alert mode", height=10, width=15, font=("Arial",14), command=lambda: alert_mode(var))
b.pack()
b2 = tk.Button(root, text="Capture mode", height=10, width=15, font=("Arial",14), command=lambda: capture_mode(var))
b2.pack()
root.mainloop()
編輯:
好,這裏是更新的代碼。我試圖弄清楚如何啓動和停止一個線程,但這並不像我想要的那樣工作。我其實不希望這兩個線程一次運行。它是警報模式或捕捉模式。重點是我不希望GUI在任何模式運行時都凍結,以便用戶可以隨時切換到其他模式。
def alert_mode(var):
print("Entering Alert Mode")
var.set("Current mode: Alert")
// do stuff that takes a while to return
def capture_mode(var):
print("Entering Capture Mode")
var.set("Current mode: Capture")
// do stuff that takes a while to return
def start_alert_thread(var):
t = threading.Thread(target=alert_mode, args=(var,))
t.start()
t.join()
def start_capture_thread(var):
t2 = threading.Thread(target=alert_mode, args=(var,))
t2.start()
t2.join()
root = tk.Tk()
var = StringVar()
var.set("Current mode: Alert")
text = tk.Label(root, text="Current mode: Alert", textvariable=var, fg="blue", font=("Arial", 18))
text.pack(pady=8)
b = tk.Button(root, text="Alert mode", height=10, width=15, font=("Arial",14), command=lambda: start_alert_thread(var))
b.pack()
b2 = tk.Button(root, text="Capture mode", height=10, width=15, font=("Arial",14), command=lambda: start_capture_thread(var))
b2.pack()
root.mainloop()
這就是我對殺戮的線程中發現,[鏈接1](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread- in-python),[link 2](http://stackoverflow.com/questions/15729498/how-to-start-and-stop-thread) –