Search code examples
pythonmultithreadinguser-interfacetkintergpio

update threaded tkinter gui


I have a small display connected to my pi. Now I have a Python script that measures the time between two events of the gpio headers. I want to display this time (the script to get this time is working perfectly). For that I created a tkinter window. There, I have a label that should display this time. I have threaded the gui function to make it possible for the program to still listen to the GPIO pin.

def guiFunc():
    gui = Tk()
    gui.title("Test")
    gui.geometry("500x200")
    app = Frame(gui)
    app.grid()
    beattime = Label(app, text = "test")
    beattime.grid()
    gui.mainloop()


gui_thread = threading.Thread(target = guiFunc)
gui_thread.start()


while True:
    time.sleep(.01)
    if (GPIO.input(3)):
        time = trigger()  #trigger is the function to trigger the 'stopwatch'
        global beattime
        beattime['text'] = str(time)
        while GPIO.input(3): #'wait' for btn to release (is there a better way?)
            print "btn_pressed"

So the program isn't doing anything since I added these lines:

global beattime
beattime['text'] = str(time)

What am I doing wrong?


Solution

  • Use tkinter.StringVar

    # omitting lines
    global timevar
    timevar = StringVar()
    timevar.set("Test")
    beattime = Label(app, textvariable=timevar)
    # omitting lines
    
    #changing the text:
    while True:
        time.sleep(.01)
        if (GPIO.input(3)):
           time = trigger()  #trigger is the    function to trigger the 'stopwatch'
           timevar.set(str(time))
           root.update() #just in case
    
           while GPIO.input(3): #'wait' for btn to release (is there a better way?)
              print "btn_pressed"
    

    And you should run the gui in your main thread. Its not recommended to call gui calls from different threads.