2017-04-18 104 views
0

我在我的簡單示例中創建了一個帶有tKinter的Python GUI我有一個觸發簡單循環的按鈕來增加計數器。我已成功地對計數器進行了線程處理,因此我的GUI不會凍結,但是我遇到了使其停止計數的問題。這是我的代碼:tKinter多線程停止線程

# threading_example.py 
import threading 
from threading import Event 
import time 
from tkinter import Tk, Button 


root = Tk() 

class Control(object): 

    def __init__(self): 
     self.my_thread = None 
     self.stopThread = False 

    def just_wait(self): 
     while not self.stopThread: 
      for i in range(10000): 
       time.sleep(1) 
       print(i) 

    def button_callback(self): 
     self.my_thread = threading.Thread(target=self.just_wait) 
     self.my_thread.start() 

    def button_callbackStop(self): 
     self.stopThread = True 
     self.my_thread.join() 
     self.my_thread = None 


control = Control() 
button = Button(root, text='Run long thread.', command=control.button_callback) 
button.pack() 
button2 = Button(root, text='stop long thread.', command=control.button_callbackStop) 
button2.pack() 


root.mainloop() 

我該如何安全地讓計數器停止遞增並優雅地關閉線程?

回答

1

你必須檢查self.stopThreadfor

+0

我應該怎麼做呢? – Vince

2

所以,你要一個for循環和while循環並行運行裏面?那麼他們不能。如你所知,for循環正在運行,並且不會注意while循環條件。

您只需要製作一個循環。如果你想要你的線程在10000個週期後自動終止,你可以這樣做:

def just_wait(self): 
    for i in range(10000): 
     if self.stopThread: 
      break # early termination 
     time.sleep(1) 
     print(i) 
+0

嘿,Johnathan謝謝,我有一個大腦放屁的時刻。 – Vince