如何在这里循环定时器?

How to While loop timer in here?

我有一个带有 while 循环的 GUI 应用程序。我在插入中断循环的 if 语句时遇到问题。我希望这是一个计时器,所以如果 60 秒内没有任何反应,while 循环就会中断。

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

如果您按照此 link 访问文档:https://pysimplegui.readthedocs.io/#persistent-window-example-running-timer-that-updates

您会发现可以使用内置的 time 模块来告诉您现在几点了。您可以计算结束时间,然后等到那时:

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

你可以用时间模块试试这个:

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

在 PySimpleGUI 中执行此操作的最简单方法是在对 window.Read() 的调用中设置 timeout 值。

此代码将等待用户输入 60 秒。如果收到 none,那么您将从 Read 调用中返回一个 "Timeout Key" 值。

请注意,您不应在 while 循环内调用 Layout。这更像是你需要的:

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