簡體   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