TAGS :Viewed: 2 - Published at: a few seconds ago

[ How to stop a python threading script using a GUI ]

I am using a GUI with a checkbox made with QT and python, when the checkbox is checked i want to display 'stackoverflow' every 5 seconds, when it is unchecked i want it to do nothing. I have tried to call the following function when it is checked:

def work (): 
    threading.Timer(5, work).start ()
    print "stackoverflow"

def checkbox(self, state):
    if state == QtCore.Qt.Checked:
        print 'checked'
        work()
    else: print 'unchecked'

But it keeps on printing 'stackoverflow'. How can i stop this?

Answer 1


Here is a solution.

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()

Answer 2


You can use variable to control thread

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