Reputation: 337
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
Upvotes: 3
Views: 2010
Reputation: 39414
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
Upvotes: 2
Reputation: 5764
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
Upvotes: 0
Reputation: 317
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
Upvotes: 1