0

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?

3
  • You are just launching one thread each time you check the checkbox, in fact you are recursively calling work in each thread, this is pretty bad, i dont know how is not even crashing :/ Commented Nov 26, 2015 at 11:10
  • Do you have any suggestion on how to make it better? Commented Nov 26, 2015 at 11:12
  • @FunkySayu answer below is a pretty good answer Commented Nov 26, 2015 at 11:20

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.