1

I want to have a function run continuously within a tkinter GUI. I have attached some shell code:

#!/usr/bin/env python3

import tkinter as tk
from time import sleep
import os
import sys

class Application(Frame):

    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()

        def create_widgets(self):
        ......

root = Tk()  

def run_continously:
    ... -- calls sleep -- ...
    root.after(3000, run_continuously)


root.geometry('%dx%d+%d+%d' % (w, h, x, y))
app = Application(root)
root.after(3000, run_continuously)          
root.mainloop()

When running the GUI it tends to run the 'run_continuously' function once and the GUI freezes up. I suspect from poking around that this is due to the sleep function (which I call in the run_continuously function)

How would I go about implementing the 'run_continuously' function in a very simple thread to get around this issue? Would running the function in a thread even get me around the problem? The 'run_continuously' function does not need to interact at all with the Application class. I want it to run simply in the background and stop when the mainloop is finished.

Here is the end of the code:

def run_continuously(quit_flag):
    print("in it")
    if not quit_flag:
        GPIO.output(DIR_PIN, True)
        for i in range(steps):
            print("in loop")
            GPIO.output(STEP_PIN, True)
            sleep(sDelay)
            GPIO.output(STEP_PIN, False)
            sleep(sDelay)
        sleep(wait_time)
        GPIO.output(DIR_PIN, False)    
        for i in range(steps):
            GPIO.output(STEP_PIN, True)
            sleep(sDelay)
            GPIO.output(STEP_PIN, False)
            sleep(sDelay)
            print("run motor")
        root.after(1000, run_continuously(quit_flag,))


#=================================================================
# main
#=================================================================

root = Tk()                            # Create the GUI root object
press1 = StringVar()
press2 = StringVar()

x = 275
y = 50
w = 580
h = 250


root.geometry('%dx%d+%d+%d' % (w, h, x, y))
app = Application(root)          # Create the root application window
quit_flag = False                
root.after(0, app.read_pressure)
motor_thread = threading.Thread(target=run_continuously, args=(quit_flag,)).start()
root.mainloop()
quit_flag=True
motor_thread.join()
6
  • Why are you calling sleep in run_continuously? What purpose does that serve? Feb 8, 2016 at 17:29
  • Why don't you try import threading and create a threading.Thread to run run_continuously?
    – user3657941
    Feb 8, 2016 at 17:40
  • the run continuously function outputs values to control a stepper motor. It uses the sleep function, but not exclusively. Feb 8, 2016 at 17:42
  • David - I tried that and the run_continuously function only executed once: Feb 8, 2016 at 17:52
  • root.after is the tk equivalent of time.sleep. In the tk thread, do not use sleep. Since your code is not an MCVE, google.com/search?q=mcve&ie=utf-8&oe=utf-8, it is impossible to experiment with you code to be sure of what is wrong. If you need pauses within run_continuously, then you may need to break it up into subfunctions to use root.after for the pausing. Feb 8, 2016 at 21:49

1 Answer 1

1

This is a minimal, complete, and verifiable example that exits cleanly if the 'QUIT' button is pressed or Ctrl-C is pressed:

from Tkinter import *
import multiprocessing
import threading
import time
import logging


class Application(Frame):
    def create_widgets(self):
        self.quit_button = Button(self)
        self.quit_button['text'] = 'QUIT'
        self.quit_button['fg'] = 'red'
        self.quit_button['command'] = self.quit
        self.quit_button.pack({'side': 'left'})

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.quit_button = None
        self.pack()
        self.create_widgets()
        self.poll()

    def poll(self):
        """
        This method is required to allow the mainloop to receive keyboard
        interrupts when the frame does not have the focus
        """
        self.master.after(250, self.poll)


def worker_function(quit_flag):
    counter = 0
    while not quit_flag.value:
        counter += 1
        logging.info("Work # %d" % counter)
        time.sleep(1.0)


format = '%(levelname)s: %(filename)s: %(lineno)d: %(message)s'
logging.basicConfig(level=logging.DEBUG, format=format)
root = Tk()
app = Application(master=root)
quit_flag = multiprocessing.Value('i', int(False))
worker_thread = threading.Thread(target=worker_function, args=(quit_flag,))
worker_thread.start()
logging.info("quit_flag.value = %s" % bool(quit_flag.value))
try:
    app.mainloop()
except KeyboardInterrupt:
    logging.info("Keyboard interrupt")
quit_flag.value = True
logging.info("quit_flag.value = %s" % bool(quit_flag.value))
worker_thread.join()
8
  • Hi David, This worked well for the most part. I added .start() after the motor_thread declaration. Running the program it works fine, but after quitting I am getting the following error: Traceback (most recent call last): File "mDS_v14.py", line 509, in <module> motor_thread.join() AttributeError: 'NoneType' object has no attribute 'join' -----See the updated code above as well. Feb 9, 2016 at 15:22
  • @RickySpanish: Review the changes in my answer. When you call start() in a chain, it returns None, so you lose your thread handle. Separate the calls as shown above to keep the thread handle. Use a while loop in run_continuously and use time.sleep instead of root.after.
    – user3657941
    Feb 9, 2016 at 16:50
  • Ok this works well, but now the motor_thread won't stop after I quit the GUI. After the user presses a QUIT button I call root.destroy() however the motor continues to run. after quitting the mainloop the quit_flag stays false Feb 9, 2016 at 17:12
  • @RickySpanish: I think you want to call root.quit() per this StackOverflow question. My guess is that root.destroy() prevents any code after root.mainloop() from running.
    – user3657941
    Feb 9, 2016 at 17:24
  • Yeah, I tried that too: after I call root.quit() the GUI freezes (doesn't quit) and the motor continues to run The only way I can get the motor to stop from running is to do a GPIO cleanup (GPIO pins controlling the step motor) Feb 9, 2016 at 17:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.