为什么只有功能有效而文本不显示?



我一直试图让用户输入秒一起倒数,一个接一个直到零。有时候,我的脑子里会冒出一些意想不到的想法。我真的很奇怪为什么没有显示文本。从现在开始感谢你的帮助。

import time
def timer():
for x in range(60,-1,-1):
print(x)
time.sleep(1.5)

input(f"Type code in {timer()} seconds : ")

什么是错…

你得到错误,因为当你调用input(f"Type code in {timer()} seconds : ")时,程序将运行timer()并尝试从中获取返回值,然后用f'Type code in {value} seconds : '打印它。

这就是为什么您将在屏幕上得到60...0的倒数,然后是Type code in None seconds :,因为timer()没有返回任何内容(None)。


What to do…

在命令提示符中呈现更新的显示并尝试同时获取用户输入是不理想的,如果不是不可能的话。(命令提示符不是为了花哨的显示。)

为了实现你的目标,我建议使用UI(用户界面),这里是一个简单的UI来做到这一点:

import tkinter as tk
class UI():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("200x50")
self.data = tk.StringVar()
self.label = tk.Label(text="")
self.entry = tk.Entry(textvariable=self.data)
self.label.pack()
self.entry.pack()

self.x = 60
self.count_down()

self.entry.bind("<Return>", self.end)
self.root.mainloop()


def count_down(self):
if self.x < 0:
self.root.destroy()
else:
self.label.configure(text=f"Type code in {self.x} seconds : ")
self.x -= 1
self.root.after(1500, self.count_down)

def end(self, keypress):
self.root.destroy()

app = UI()
value = app.data.get()
# do whatever you want with value
print('value : ',value)

正如tdelaney和DarryIG在评论中所说,在执行代码片段时,它将输出60,59,58…,直到0,然后显示"Type code in None seconds: ",我认为这是正确的结果。只有在{}中放置一个简单的表达式(如变量),代码片段才能将表达式和文字一起输出。

Time = 5
input(f"Type code in {Time} seconds : ")

上面的代码片段将输出"在5秒内键入代码:">

最新更新