0

我有一个程序在运行时需要对模块进行输入,所以我正在实现一个简单的对话框来从用户那里获取输入以在我的 Tkinter 程序中使用。但是我也需要它在将模块作为控制台程序运行时超时,在用户不与它交互的几秒钟后通过它或超时。而不是让它坐在那里永远等到用户与之交互。超时后如何终止窗口?这是我现在所拥有的......


def loginTimeout(timeout=300):
    root = tkinter.Tk()
    root.withdraw()
    start_time = time.time()
    input1 = simpledialog.askinteger('Sample','Enter a Number')
    while True:
        if msvcrt.kbhit():
            chr = msvcrt.getche()
            if ord(chr) == 13: # enter_key
                break
            elif ord(chr) >= 32: #space_char
                input1 += chr
        if len(input1) == 0 and (time.time() - start_time) > timeout:
            break

    print('')  # needed to move to next line
    if len(input1) > 0:
        return input1
    else:
        return input1
4

1 回答 1

0

不完全确定问题是什么,但您可以after()以与此类似的方式使用 tkinter 方法:

import tkinter as tk

root = tk.Tk()
root.geometry('100x100')

def get_entry() -> str:
    """Gets and returns the entry input, and closes the tkinter window."""
    entry = entry_var.get()
    root.destroy() # Edit: Changed from root.quit()
    return entry

# Your input box
entry_var = tk.StringVar()
tk.Entry(root, textvariable=entry_var).pack()

# A button, or could be an event binding that triggers get_entry()
tk.Button(root, text='Enter/Confirm', command=get_entry).pack()

# This would be the 'timeout'
root.after(5000, get_entry)

root.mainloop()

因此,如果用户输入内容,他们可以点击确认或启动绑定到该条目的事件,或者在延迟之后程序运行 get_entry。也许这会给您一个想法,您还可以查看其他小部件方法: https ://effbot.org/tkinterbook/widget.htm

编辑:我不确定这在你的程序中是如何安排的,但是root.mainloop()会阻塞,所以一旦它运行,它之后的代码将不会运行,直到 mainloop() 退出。如果您的函数是 toplevel() 窗口的一部分,您可以使用它wait_window()来阻止函数前进,直到您的超时破坏顶层窗口或用户之前调用该函数。这个例子虽然可能不是最好的解决方案,但应该是:

def loginTimeout(timeout_ms: int=5000):
    root = tk.Tk()
    root.geometry('200x50')

    # function to get input and change the function variable
    input_ = ''
    def get_input():
        nonlocal input_
        input_ = entry_var.get()
        root.destroy()

    # build the widgets
    entry_var = tk.StringVar()
    tk.Entry(root, textvariable=entry_var).pack(side='left')
    tk.Button(root, text='Confirm', command=get_input).pack(side='right')

    # timeout
    root.after(timeout_ms, get_input)

    # mainloop
    root.mainloop()

    # won't get here until root is destroyed
    return input_

print(loginTimeout())
于 2019-10-28T18:37:52.233 回答