Home  >  Q&A  >  body text

Python如何实现倒计时效果?

我在尝试写个命令行的fm,但是碰到播放时间的适合遇到了问题,如何实现一个计时器,每次自减1秒后覆盖之前的print 输出
我想把歌曲总时间传入如下代码,封装个函数,但是如何覆盖上一次print的结果呢?

def remain(min)
    count = 0
    while (count < min):
        count += 1
        n = min - count
        time.sleep(1)
        print n   
PHPzPHPz2718 days ago387

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:05:58

    First of all, "r" means the cursor returns to the beginning of the line (refer to the ascii encoding table). You can use it to achieve the effect of overwriting characters, but only if you don't break lines (eliminate n).
    Come~ and see the miracles of our Lord.

    pythonline = "============================="
    print(line + "\r" + line, end='');print("\r" + line + "\r" + line)
    

    Add a progress bar demo

    pythonimport time
    lineLength = 20
    delaySeconds = 0.05
    frontSymbol = '='
    frontSymbol2 = ['—', '\', '|', '/']
    backSymbol  = ' '
    
    for i in range(10):
        lineTmpla = "{:%s<%s} {} {:<2}"%(backSymbol, lineLength)
        for j in range(lineLength):
            tmpSymbol = frontSymbol2[j%(len(frontSymbol2))]
            print("\r" + lineTmpla.format(frontSymbol * j, tmpSymbol, j), end='')
            time.sleep(delaySeconds)
    

    reply
    0
  • Cancelreply