如何在这里的While循环计时器?

时间:2019-04-26 09:07:46

标签: python loops timer pysimplegui

我有一个带有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

3 个答案:

答案 0 :(得分:1)

如果您点击以下指向文档的链接: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

答案 1 :(得分:1)

您可以使用时间模块尝试此操作:

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

答案 2 :(得分:0)

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

此代码将等待用户输入60秒钟。如果未收到任何消息,那么您将获得Read调用返回的“超时密钥”值。

请注意,您不应在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