Skip to main content
 首页 » 编程设计

python之为什么代码在 python 中停止在 input()之有什么好处

2024年10月25日7tuyile006

正如任何人都知道的那样,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 处暂停,这主要有什么好处?

当然,如果我们可以解决这个问题(对于我认为的任何事情),那么让代码像那样坚持下去是愚蠢的。欢迎大家发表意见,说出你的看法。

请您参考如下方法:

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

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

如果这是在没有暂停的情况下运行,你会得到一个错误 input1 is not defined,所以暂停是至关重要的。希望这对您有所帮助。