【问题标题】:Why does code stop at input() in python - what are the benefits?为什么代码在 python 中的 input() 处停止 - 有什么好处?
【发布时间】: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


【解决方案1】:

也许应该有一个内置函数来禁用暂停。这将使多线程更容易,但是当您必须测试一些使用输入创建的变量时,暂停很方便:

input1 = input("enter a big number")
if input1 >= 8:
    print("That is a big number")
else:
    print("That is tiny...")

如果在没有暂停的情况下运行,您将收到错误 input1 is not defined,因此暂停至关重要。希望这会有所帮助。

【讨论】:

    【解决方案2】:

    一个好处?如果您的代码遇到应该设置的变量,但由于用户尚未输入值而不存在,则会引发错误。例如:

    legal_age = 21
    age = int(input("Your age: "))
    
    if age >= legal_age:
        print("You can drink legally!")
    else:
        print("You can't drink yet!")
    

    一个基本示例,但仍然如此 - 如果年龄变量还没有值,Python 将如何使用它,因为它没有暂停等待输入?

    不过,线程可以相当容易地用于您希望在输入之后发生的进程。

    【讨论】:

    • 是的,这是有道理的,我意识到了这一点,并认为保留在这里很有用,但也应该有其他选择。
    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多