如何打印倒计时器并同时接受用户输入(python)?

How to print countdown timer and accept user input at the same time (python)?

澄清

这是对我之前问题的重新回答post,因为我非常渴望得到我的问题的答案。我是新手,如果这违反了任何规则,请通知我,如果是这样,我会删除它。post。

我想创建一个类似测验的程序,用户可以在其中看到倒数计时器每秒滴答作响,同时他们可以随时输入答案。根据我之前关于这个问题的post,我已经尝试在我的代码中使用线程。这是我的代码示例。

from threading import Thread
import time
import sys

def func1():
    t = 10
    for t in range (t,1,-1):
        sys.stdout.write('\r' + str(t))
        sys.stdout.flush()
        time.sleep(1)
        
if __name__ == '__main__':
    Thread(target = func1).start()
    answer = input("\tEnter: ")

它确实起作用,但问题是用户输入被强制返回 return (\r) 而计时器没有正确删除 10 的“0”,这不是我想要的欲望。这是输出:

如果您能提出解决此问题的建议,那将是一个巨大的帮助。提前谢谢你。

经过一番折腾,我想到了这个。 如果您希望我编辑它以使其在没有 windows 的情况下工作,请告诉我。

import time
import tkinter
from tkinter import messagebox
from tkinter import *
from tkinter import ttk
from threading import Thread

def clear():
    print('3[H3[J', end='')
  
run = True

def timer():
    tim = int(input("Type how long the countdown should last in seconds: "))
    clear()
    count = 0
    while count < tim and run == True:
        clear()
        b1 = (tim-count)
        c = (str(b1),"second(s) left")
        win = Tk()
        win = Tk()
        win.attributes('-fullscreen', True)
        if run == False:
            win.destroy()
        Label(win, text= c,
        font=('Helvetica 20 bold')).pack(pady=20)
        win.after(1000,lambda:win.destroy())
        win.mainloop()
        time.sleep(1)
        count += 1
      
def take_input():
    inpu = input()
    #Your code
  
def time_input():
    global run
    while run == True:
        t1 = Thread(target=timer)
        t2 = Thread(target=take_input)
        
        t1.start()
        t2.start()
        
        t2.join()
        thread_running = False
        run = False
      
time_input()

希望这对您有所帮助,不客气。乂婉丨卐乜尺 (要阻止 window 全屏,请将 (window).attributes('-fullscreen', True) 更改为 (window).geometry(500x500) 或任何您想要的。