【问题标题】:while loop for overwrite resultwhile循环覆盖结果
【发布时间】:2019-12-19 16:04:20
【问题描述】:

我正在编写简单的代码来倒计时并且无法覆盖时间。 结果以一行形式出现(如 00:00:0200:00:01),我希望它堆叠起来看起来像一个实际的时钟

print(time_left,end="")

这是我所做的,我将\r 设置为

print("time_left + "\r", end="")

没有成功

import time
while True:
    uin = input(">> ")
    try:
            when_to_stop = abs(int(uin))
    except KeyboardInterrupt:
            break
    except:
            print("Not a number!")

while when_to_stop > 0:
        m, s = divmod(when_to_stop, 60)
        h, m = divmod(m, 60)

           #.zfill(2) to make 00:00:00 form
        time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)
        print(time_left + '\r', + end="")
        time.sleep(1)
        when_to_stop -= 1 

print()

【问题讨论】:

    标签: python python-3.x loops while-loop python-3.7


    【解决方案1】:

    你需要使用

    print(time_left,end='\r')
    

    end='\r' 将光标返回到行首。因此,当您再次打印相同的内容时,它会覆盖。

    【讨论】:

    • 嗨,感谢您的评论!结果以 00:00:03 00:00:02 00:00:01 的形式出现,看起来不错,但不完全是我想要的,我的意思是一条会溢出的单行
    【解决方案2】:

    我也会重新设计while 循环(只是为了“美”)。所以你不需要使用break。只需检查该值是否不为零,并仅在解析成功时设置该值。

    when_to_stop = 0
    while(when_to_stop == 0):
        uin = input(">> ")
        try:
            when_to_stop = abs(int(uin))
        except:
            print("Not a number!")
    
    print(when_to_stop)
    

    【讨论】:

      【解决方案3】:

      如果你使用IDLE,“\r”不起作用,你必须用其他东西打开你的程序,或者你也可以双击你的程序打开它而不用编辑,你会看到覆盖。

      【讨论】:

        猜你喜欢
        • 2013-09-27
        • 2014-12-05
        • 1970-01-01
        • 1970-01-01
        • 2018-06-29
        • 2014-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多