简体   繁体   English

如何在一定时间后终止 function 调用

[英]how to kill a function call after a certain amount of time

def input():
  sg.theme('TanBlue')
  event, values = sg.Window('Login Window',
              [[sg.T('Please Enter your email'), sg.In(key='-ID-')],
              [sg.B('OK'), sg.B('Cancel') ]]).read(close=True)


  login_id = values['-ID-']
  return login_id

I have this simple function written in python, it a small GUI that pops up to take input from a user.我有一个用 python 编写的简单 function,它是一个小 GUI,可以弹出以接受用户的输入。 but what I'm trying to do is, after a certain amount of time lets say 10 seconds.但我想做的是,在一定时间后让我们说 10 秒。 if no input is given I want to close the GUI and use a default value for the intended input.如果没有输入,我想关闭 GUI 并为预期输入使用默认值。 my entire script pauses using this GUI, if no input is given then the script won't continue.我的整个脚本使用这个 GUI 暂停,如果没有输入,那么脚本将不会继续。 I do not want that, but I can't figure out how to implement this.我不想要那个,但我不知道如何实现它。 I tried using the signal in python, but I'm on windows 10 and I couldn't integrate it correctly.我尝试使用 python 中的信号,但我在 windows 10 上,我无法正确集成它。 I would like a universal solution for this Thanks我想要一个通用的解决方案谢谢

input is a keyword in Python and thus shouldn't be used as a function name. input是 Python 中的关键字,因此不应用作 function 名称。

You can add a timeout on your read call.您可以在读取调用中添加超时。

This example will give the user 3 seconds to fill in a value and press OK:此示例将给用户 3 秒的时间来填写一个值并按 OK:

import PySimpleGUI as sg

def timed_input():
    sg.theme('TanBlue')
    event, values = sg.Window('Login Window',
                              [[sg.T('Please Enter your email'), sg.In(key='-ID-')],
                               [sg.B('OK'), sg.B('Cancel')]]).read(timeout=3000, close=True)
    if event == sg.TIMEOUT_KEY:
        print('Timed out')
        login_id = None
    else:
        login_id = values['-ID-']
    return login_id

print(timed_input())

Nice use of the shortened element names and close parameter.很好地使用缩短的元素名称和关闭参数。 I've not seen a timeout with a close parameter before.我以前没有看到过关闭参数的超时。 Interesting combination.有趣的组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM