【发布时间】:2014-08-02 07:08:53
【问题描述】:
任何人都知道 python 将在input() 处停止或暂停,这使得在超时时很难获得输入,这是可能的:
import tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
def well():
whatis = entrybox.get()
if whatis == "": # Here you can check for what the input should be, e.g. letters only etc.
print ("You didn't enter anything...")
else:
print ("AWESOME WORK DUDE")
app.destroy()
global label2
label2 = tk.Button(text = "quick, enter something and click here (the countdown timer is below)", command = well)
label2.pack()
entrybox = tk.Entry()
entrybox.pack()
self.label = tk.Label(self, text="", width=10)
self.label.pack()
self.remaining = 0
self.countdown(10)
def countdown(self, remaining = None):
if remaining is not None:
self.remaining = remaining
if self.remaining <= 0:
app.destroy()
print ("OUT OF TIME")
else:
self.label.configure(text="%d" % self.remaining)
self.remaining = self.remaining - 1
self.after(1000, self.countdown)
if __name__ == "__main__":
app = ExampleApp()
app.mainloop()
我真正的问题是为什么代码会在input 处暂停,主要有什么好处?
当然,如果我们能解决这个问题(对于我认为的任何事情),那么让代码保持这样是愚蠢的。欢迎大家发表意见,发表你的看法。
【问题讨论】:
-
好的,请不要轻易投反对票,我知道这将是一个有争议的问题,但它肯定还是有一些相关性......
-
你读过documentation on the
input()function吗?您能否向我们解释一下您在使用该函数时预期会发生什么,以及应该发生什么而不是暂停? -
我现在...好吧,我想我希望它可能有一个可以禁用暂停的内置选项,我想暂停通常是必不可少的,因为设置为在给出输入之前不能使用输入,但对于其他目的(如超时输入),没有暂停可能很方便。
-
但是你这里有一个GUI;您通常不使用标准输入(控制台)作为 GUI 的输入,而是使用小部件(按钮、输入框等)来获取用户输入。
input()不是你想要的工具。 -
正如 Martijn 所写,
input()用于控制台(命令行)应用程序,而不是用于 GUI 应用程序。print()函数也不适合那里。当从控制台启动应用程序或将标准输出捕获到其他窗口时,它们可能偶尔用于调试 GUI 应用程序。
标签: python python-3.x input timeout