【问题标题】:How to make a countdown timer that runs in the background, which terminates the program when it runs out?如何制作一个在后台运行的倒数计时器,当程序用完时终止程序?
【发布时间】:2016-04-21 17:06:12
【问题描述】:

我正在使用图形在 Python 中制作《谁想成为百万富翁》游戏。我希望用户每个问题有 45 秒的时间来回答它。但是,每当我在我的代码中放置一个计时器时,它首先会等待 45 秒,然后 让用户回答,而不是在后台运行并让用户同时回答。

【问题讨论】:

  • 发布给您带来问题的代码。
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布代码并准确描述问题之前,我们无法有效地帮助您。 StackOverflow 不是编码或教程服务。

标签: python


【解决方案1】:

使用threading 模块一次运行多个线程

您可以使用 Python threading 模块让两件事同时发生,从而允许用户在计时器计时结束时回答

一些使用这个的示例代码:

from threading import Thread
from time import sleep
import sys

def timer():
    for i in range(45):
        sleep(1)   #waits 45 seconds
    sys.exit() #stops program after timer runs out, you could also have it print something or keep the user from attempting to answer any longer

def question():
    answer = input("foo?")

t1 = Thread(target=timer)
t2 = Thread(target=question)
t1.start() #Calls first function
t2.start() #Calls second function to run at same time

它并不完美,但这段代码应该启动两个不同的线程,一个是问一个问题,一个是在终止程序前 45 秒超时。有关threading 的更多信息,请访问the docs。希望这对您的项目有所帮助!

【讨论】:

  • 所以我把我的代码放在问题函数中并调用它,但它说主线程不在主循环中......
  • 显然,如果您使用图形,则控制图形的代码必须在主线程中。也许尝试在计时器线程之前启动问题线程?如果您使用的是 Python 3.4 或更高版本,请尝试assert threading.current_thread() == threading.main_thread() 来检查一个线程是否为主线程。另请参阅this question 和/或this question
【解决方案2】:

尝试使用 time.time()。这将返回 UNIXTime 中自 1970 年 1 月 1 日以来的秒数。然后,您可以创建一个 while 循环:

initial_time = time.time()
while time.time()-initial_time < 45:
    #Code

希望这有帮助!

【讨论】:

    猜你喜欢
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多