3

I have a GUI app with a while loop. I'm having trouble inserting an if statement that breaks the loop. I want this to be a timer so if nothing happens in 60 seconds the while loop will break.

layout = [[sg.Text('Velg mappe som skal tas backup av og hvor du vil plassere backupen')],
          [sg.Text('Source folder', size=(15, 1)), sg.InputText(a), sg.FolderBrowse()],
          [sg.Text('Backup destination ', size=(15, 1)), sg.InputText(b), sg.FolderBrowse()],
          [sg.Text('Made by XXX™')],
          [sg.Submit("Kjør"), sg.Cancel("Exit")]]
window = sg.Window('Backup Runner v2.1')
while True:  # Event Loop
    event, values = window.Layout(layout).Read()
    if event in (None, 'Exit'):
        sys.exit("aa! errors!")
        print("Skriptet ble stoppet")
    if event == 'Kjør':
        window.Close()
        break

quamrana
  • 37,849
  • 12
  • 53
  • 71
Kickdak
  • 197
  • 1
  • 3
  • 15

3 Answers3

2

If you follow this link to the docs: https://pysimplegui.readthedocs.io/#persistent-window-example-running-timer-that-updates

You will see that you can use the built-in time module to tell you what the time is now. You could calculate the end time and just wait til then:

import time

layout = ...
window = sg.Window('Backup Runner v2.1').Layout(layout)

end_time = time.time() + 60

while True:  # Event Loop
    event, values = window.Read(timeout=10)
    # Your usual event handling ...

    if time.time() > end_time:
        break
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • You should not be calling window.Layout inside of your event loop. It should be called only one time. In your event loop, the call should be window.Read(timeout=10). You can specify the layout in the call to Window itself. It's the second parameter. – Mike from PSG Apr 28 '19 at 17:26
  • Ok, having re-read the docs (I don't know this framework at all), I'll update my answer to indicate this. – quamrana Apr 28 '19 at 17:34
1

You could try this with time module:

import time

seconds = int(time.time()) # This is seconds since epoch
while True:
    if int(time.time()) > seconds + 60: # True when seconds + 60 < current seconds
        break # End of your loop
HLupo
  • 317
  • 3
  • 12
0

The simplest way in PySimpleGUI to do this is to set the timeout value in the call to window.Read().

This code will wait for user input for 60 seconds. If none is received, then you will get a "Timeout Key" value returned to you from the Read call.

Note that you should not be calling Layout inside of your while loop. This is more like what you need:

while True:  # Event Loop
    event, values = window.Read(timeout=60*1000)
    if event in (None, 'Exit'):
        sys.exit("aa! errors!")
        print("Skriptet ble stoppet")
    if event == 'Kjør':
        window.Close()
        break
    if event == sg.TIMEOUT_KEY:
        break
Mike from PSG
  • 5,312
  • 21
  • 39