3

i'm trying to create a big clock as a gui test project. The window should run without any input and just display the time while updating 10 times a second. Regardless of what i tried so far i cannot get the text to update with my current time.

Here's my code:

import PySimpleGUI as gui
import time

gui.theme('Reddit')

clockFont = ('Arial', 72)

layout = [  
            [gui.Text('Loading...',size=(8,2), justification='center', key='CLK', font=clockFont)]
]

window = gui.Window('Big Clock', layout, size=(500, 150), finalize=True)

window.Resizable = True
while True:
    event, values = window.read()
    print(event)
    if event in (None, gui.WIN_CLOSED):
        break
    if event == 'Run':
        currentTime = time.strftime("%H:%M:%S")
        window['CLK'].update(currentTime)
        window.refresh()
        time.sleep(0.1)
window.close()

Additionally someone on StackOverflow said in a post that one should not use time.sleep() in a looped environment. What should i use instead?

ThisLimn0
  • 43
  • 5
  • Right on the time.sleep in a GUI's event loop. Jason has the "right" answer... use a timeout on your read. You have also chosen a "right" approach of using the time module to get the time to display rather than relying on how often the loop runs (the time displayed will drift if you do this). There are Demo Programs that implement similar timers but with buttons. – Mike from PSG Apr 30 '22 at 12:49

1 Answers1

4

Where the event 'Run' come from ?

Try to use option timeout in method window.read to generate event sg.TIMEOUT_EVENT.

timeout

Milliseconds to wait until the Read will return IF no other GUI events happen first

You can also use multithread for time.sleep and call window.write_event_value to generate event to update the GUI.

import PySimpleGUI as gui
import time

gui.theme('Reddit')

clockFont = ('Arial', 72)

layout = [
    [gui.Text('Loading...',size=8, justification='center', key='CLK', font=clockFont)]
]

window = gui.Window('Big Clock', layout, finalize=True)

while True:

    event, values = window.read(timeout=100)

    if event in (None, gui.WIN_CLOSED):
        break

    if event == gui.TIMEOUT_EVENT:
        currentTime = time.strftime("%H:%M:%S")
        window['CLK'].update(currentTime)

window.close()
Jason Yang
  • 11,284
  • 2
  • 9
  • 23