简体   繁体   English

如何显示倒数计时器并同时接受用户输入(python)?

[英]How do you display a countdown timer and accept user input at the same time (python)?

Hello Everyone大家好

This is my first time posting my concern on this platform so please excuse my horrendous way of asking questions.这是我第一次在这个平台上发布我的问题,所以请原谅我可怕的提问方式。 Also, I want to thank you all for having a peek at my difficulties.另外,我要感谢大家看到我的困难。

Currently, I want to create a quiz-like algorithm that would display a countdown timer that ticks down every second while the user can input their answer anytime.目前,我想创建一个类似测验的算法,该算法将显示一个每秒倒数一次的倒数计时器,而用户可以随时输入他们的答案。 Here is a sample of my code:这是我的代码示例:

import time

chance = 2

def countdown(t):
    while t > 0:
        secs = t % 60
        timer = "{:02d}".format(secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1

while chance > 0:
    print("Type '1'")
    countdown(int(10)
    answer = input("Enter: ")

    if answer == 1:
        print("Correct")
        break

    elif t == 0:
        print("Time over")
        break

    else:
        chance = chance - 1
        print("Wrong")

Desired result:期望的结果:

  • If the user writes an invalid answer, another chance would be given and the time countdown resets.如果用户写了一个无效的答案,则会再给一次机会,并且倒计时会重置。
  • The countdown should remain in the console ticking down and printing the result every second倒计时应该保留在控制台中滴答作响并每秒打印一次结果
  • The input would still be over there so that the user can type the answer at any time possible.输入仍会在那里,以便用户可以随时键入答案。

Not to exclude, the code doesn't work due to some syntax errors (I am not a good coder D:, sorry).不排除,由于某些语法错误,代码无法正常工作(我不是一个好的编码员 D:,抱歉)。 I would be glad to see other great samples of code that have the exact purpose as my intention or some piece of advice to fix this code.我会很高兴看到其他很棒的代码示例,它们的目的与我的意图完全相同,或者是一些修复此代码的建议。

Once again, I would like to thank you for reading through my trouble and I hope you could provide me with some solid solutions to solve this situation.再次感谢您阅读我的麻烦,希望您能为我提供一些可靠的解决方案来解决这种情况。

As you've mentioned, there are several syntax errors in your code, I'll let you figure those out for yourself (hint for one of them: you shouldn't print a function).正如你所提到的,你的代码中有几个语法错误,我会让你自己找出这些错误(提示其中之一:你不应该print一个函数)。

What you want here is two functions to run simultaneously (the timer running in the background while the input functions runs in forefront).你想要的是同时运行两个函数(定时器在后台运行,而输入函数在最前面运行)。 So look up how to do threading with python. Useful resource for Timer Threading in Python: https://www.educba.com/python-threading-timer/因此,请查看如何使用 python 进行线程处理。Python 中定时器线程处理的有用资源: https://www.educba.com/python-threading-timer/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM