繁体   English   中英

如何创建 Python 计时器倒计时?

[英]How to create a Python timer to count down?

我的代码:

def timer():
    while True:
        try:
           when_to_stop = 90
        except KeyboardInterrupt:
             break
        except:
             print("error, please star game again")
        while when_to_stop > 0:
            m, s = divmod(when_to_stop, 60)
            h, m = divmod(m, 60)
            time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + 
            str(s).zfill(2) # got cut off, belongs to the line before this
            print("time:", time_left + "\r", end="")
            if time_left == 0:
               print("TIME IS UP!")
            time.sleep(1)
        when_to_stop -= 1

这工作得很好,除了 time.sleep 意味着我的整个程序都在睡觉,所以在那之后的任何事情都会停止 90 秒。 有什么办法可以解决这个问题?(或者制作一个没有时间的新计时器。睡眠?)

我认为,或者,您可以跟踪计时器的启动时间,并通过查看经过的时间是否比计时器应该持续的时间长来检查时间。 我不确定您对 Python 中的类和对象了解多少,但想到的解决方案如下:

import datetime

class Timer:
  def __init__(self,**kwargs):
      self.start = datetime.datetime.now()
      self.length = datetime.timedelta(**kwargs)
      self.end = self.start+self.length
  def isDone(self):
      return (self.end-datetime.datetime.now()).total_seconds()<=0
  def timeLeft(self):
      return self.end-datetime.datetime.now()
  def timeElapsed(self):
      return datetime.datetime.now()-self.start

即使你不太了解 class 本身,如果你把它放在你的代码中,它应该会像一个魅力一样工作:

#This has the same options as:
#class datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
t = Timer(days=2)

while(not t.isDone()):
  #Do other game stuff here....
    time_left = t.timeLeft()
    print(f"time: {time_left}")
    #And here....
print("Done now")

暂无
暂无

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

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