Search code examples
pythonloopstimerpysimplegui

How to While loop timer in here?


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


Solution

  • 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