我正在使用带有QT和python复选框的GUI,当选中该复选框时,我想显示' stackoverflow'每隔5秒,当它被取消选中时,我希望它什么都不做。我在检查时尝试调用以下函数:
def work ():
threading.Timer(5, work).start ()
print "stackoverflow"
def checkbox(self, state):
if state == QtCore.Qt.Checked:
print 'checked'
work()
else: print 'unchecked'
但它继续印刷' stackoverflow'。我怎么能阻止这个?
答案 0 :(得分:1)
这是一个解决方案。
from threading import Thread
import time
class WorkerThread:
def __init__(self, timer=5):
self.timer = timer
self._alive = False
def work(self):
while self._alive:
time.sleep(self.timer)
print("Stack Overflow")
def start(self):
self._thread = Thread(target=self.work)
self._alive = True
self._thread.start()
def stop(self):
self._alive = False
worker_thread = WorkerThread()
def checkbox(self, state):
if state == QtCore.Qt.Checked:
worker_thread.start()
else:
worker_thread.stop()
答案 1 :(得分:0)
您可以使用变量来控制线程
running = False
def work ():
print "stackoverflow"
if running:
threading.Timer(5, work).start ()
def checkbox(self, state):
global running
if state == QtCore.Qt.Checked:
print 'checked'
running = True
work()
else:
print 'unchecked'
running = False