python 3.4、定时器倒计时不工作

python 3.4, timer count down not working

我想创建一个以小时、分钟和秒为单位倒计时的时钟,但由于某种原因无法正常工作,有人可以帮助我吗

def countdown():
  times = 1
  th = 1
  tm = 0
  ts = 0
  while times != 0:
    if (ts>0 or tm>0 or th>0):
      print ('it run for ' + str(th) + ' Hours ' + str(tm) + ' Minutes ' + str(ts) + ' Seconds ')
      time.sleep(1)
      ts = ts - 1
      if (ts==0 and (tm>0 or th>0)):
        ts = 59
        tm = tm - 1
        if(ts==0 or tm==0 and th>0):
          ts = 59
          tm = 59
          th = th - 1
          if (ts==0 and tm==0 and th==0):          
            times = 0
  else:
    print ('stopped')
    ts = 0
    tm = 0
    th = 0

countdown()

谢谢

一个更简单的方法是使用 datetimetime.sleep

在一个函数中,您可以在其中传递天数、小时数、分钟数和秒数以进行倒计时:

from datetime import datetime, timedelta
import time

def countdown(d=0, h=0, m=0, s=0):
    counter = timedelta(days=d, hours=h, minutes=m, seconds=s)
    while counter:
        time.sleep(1)
        counter -= timedelta(seconds=1)
        print("Time remaining: {}".format(counter))

5秒倒计时示例:

In [2]: countdown(s=5)
Time remaining: 0:00:04
Time remaining: 0:00:03
Time remaining: 0:00:02
Time remaining: 0:00:01
Time remaining: 0:00:00

两小时:

In [3]: countdown(h=2)
Time remaining: 1:59:59
Time remaining: 1:59:58
Time remaining: 1:59:57
Time remaining: 1:59:56
Time remaining: 1:59:55
Time remaining: 1:59:54
import datetime
import time

def countdown():
  count = datetime.timedelta(hours=1)
  while count:
    print ('it run for ' + str(count))
    time.sleep(1)
    count -= datetime.timedelta(seconds=1)

  print ('stopped')

countdown()