2017-04-18 108 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