我有一个程序,该程序在运行时需要输入模块,因此我正在实现一个简单的对话框,以从用户那里获取输入,以在我的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
不能完全确定问题是什么,但可以类似的方式使用tkinter after()
方法:
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.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