0

I'm trying to start a thread (without understanding what threads are) that will call a function from a different python file every second, and set a label's text attribute to the str that it returns. The result would a be a label that every second is updated to show the current time. I could use a while True loop but that would stop the succesive code from running, including Tkinter's Tk.mainloop(). I've seen a lot of questions about this topic on SO but haven't gotten any solution to work so far.

What python method can start a process that continually calls an external function? And should this be before or after the mainloop()? What exactly is that mainloop() loop doing? The python program continues yet somehow Tkinter is still able to check for events?

Running Python 3.4

AllTradesJack
  • 2,762
  • 5
  • 25
  • 36
  • Though it's not EXACTLY a duplicate, check out [this question](http://stackoverflow.com/questions/2400262/code-a-timer-in-a-python-gui-in-tkinter) which is definitely *DUPLICATE-ESQUE* – Adam Smith Jun 25 '14 at 23:02

1 Answers1

3

This is how I'd do it. Well no, I'd probably wrap it into a class and instantiate the class but then I'm really just stealing whole-cloth from the linked question

import tkinter as tk
import customfunc

def run():
    root = tk.Tk()
    s_var = tk.StringVar()
    tk.Label(root, textvariable = s_var).pack()

    def update_time():
        s_var.set(customfunc.func())
        root.after(1000, update_time)

    update_time()
    root.mainloop()

if __name__ == "__main__":
    run()
Community
  • 1
  • 1
Adam Smith
  • 52,157
  • 12
  • 73
  • 112