我正在建立一个时间倒计时器。我只想每次更新'时间',而不是一次又一次地打印整个事物。循环一次又一次地打印相同的东西。比如,假设我要打印1到10.输出将是 1 2 3 4 5 ...但我想要 1(然后将删除1) 2(它将被删除,下一个将被打印)
答案 0 :(得分:1)
\r
首先打印回车符,因此remain_time
打印在上一行的顶部。
import sys #Added
import time
while True:
now= time.time()
current_time= (time.asctime())
current_hour= current_time[11:13]
current_minute= current_time[14:16]
current_second= current_time[17:19]
remain_hour= 23 - int(current_hour)
remain_minute= 60 - int(current_minute)
remain_second= 60 - int(current_second)
remain_time= "%sh %sm and %ss remaining" %(str(remain_hour),str(remain_minute), str(remain_second))
sys.stdout.write('\r'+remain_time) #Changed
#print('\r'+remain_time,end="") #Alternatively you can also use this
time.sleep(1) #Changed