-2

I want to periodically update a text window with the current time at a rate of about 1 sec. Can't figure out how to periodically get time and update text window. put a loop both before and after mainloop(). neither work.

# Siderial Time Calculation

from Tkinter import *
import time as tm
from time import strftime
from PyAstronomy import pyasl
import datetime

root = Tk()

st=strftime("%a, %d %b %Y %H:%M:%S +0000 %Z", tm.gmtime())
print 'st',st[17:25]

mytext = Text(root, background='#101010', foreground="#D6D6D6", borderwidth=18, relief='sunken',width=16, height=5 )
mytext.insert(END, st)
mytext.grid(row=0, column=0, columnspan=6, padx=5, pady=5)

root.mainloop()

With infinite loop before mainloop Text widget does not appear. With infinite loop after mainloop widget appears but no text window update.

furas
  • 134,197
  • 12
  • 106
  • 148
  • There are lots of questions on this site related to creating clocks and timers in tkinter. Have you done any research? – Bryan Oakley Jul 15 '19 at 02:16

1 Answers1

0

This code use after() to run function with delay.

Because after() runs function only once (or rather it sends this function to mainloop which executes it only once) so you have to use it again and again in executed function. You can do it at beginning or at the end of this function.

import Tkinter as tk
import time

# --- functions ---

def update_time():
    # run again after 1000ms (1s)
    root.after(1000, update_time)

    st = time.strftime("%a, %d %b %Y %H:%M:%S +0000 %Z", time.gmtime())
    print 'st:', st[17:25]

    #mytext.delete(0, 'end')
    mytext.insert('end', st)
    mytext.insert('end', '\n')

# --- main ---

root = tk.Tk()

mytext = tk.Text(root)
mytext.grid(row=0, column=0)

# run first time without delay
update_time()

# run first time with delay
#root.after(1000, update_time)

root.mainloop()
furas
  • 134,197
  • 12
  • 106
  • 148