0

I am new to Python and tkinter. Below I made a very short program where the label in a Tkinter GUI should update every 10 secs. Alas it doesn't do that.

Can somebody explain why not please? Also, if I click the little 'x' in the top right corner, the program doesn't stop cleanly as expected.

from tkinter import *
import time

root = Tk()
root.title("P2Server")
var = StringVar()
label = Label( root, textvariable = var)
var.set("This is the start string - should be overwritten every 10 secs")
label.pack()

def startProcess():
    UPDATE_PERIOD = 10 #seconds
    startTime = time.time();
    cntr = 1
    while True:
        print("Loop " + str(cntr))
        var.set("Loop " + str(cntr))
        label.pack()
        cntr = cntr + 1
        time.sleep(UPDATE_PERIOD - ((time.time() - startTime) % UPDATE_PERIOD))

root.after(100, startProcess)
root.mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301
mkemper
  • 57
  • 6

2 Answers2

1

You should not use time.sleep() inside the tkinter GUI. It is much better to use

root.after(milliseconds, callback)

to call your function after a certain time.

Matiiss
  • 5,970
  • 2
  • 12
  • 29
1

Try this. Don't use while loop in tkinter. mainloop is a sort of a loop which gets interrupted. Take a look at after()

def startProcess(cntr):
    var.set("Loop " + str(cntr))
    
    root.after(10000,startProcess,cntr+1)

root.after(100, startProcess,1)
root.mainloop()