2014-03-13 155 views
0

这是我写的一个简单的番茄钟计时器。理论上,它会无限地运行,在25分钟和5分钟的时间之间交替。为什么这个脚本不循环/只运行一次?

import time 
import sys 
import datetime 
import winsound 

def ring(sound): 
    winsound.PlaySound('%s.wav' % sound, winsound.SND_FILENAME) 

times = 0 

while True: 
    tomato = 0 
    while tomato <= 1500: 
     timeLeft = 1500 - tomato 
     formatted = str(datetime.timedelta(seconds=timeLeft)) 
     sys.stdout.write('\r'+ formatted) 
     time.sleep(1) 
     tomato += 1 
    ring("MetalGong") 

    fun = 0 
    while fun <= 300: 
     funTimeleft = 300 - fun 
     funFormatted = str(datetime.timedelta(seconds=funTimeleft)) 
     sys.stdout.write('\r'+ funFormatted) 
     time.sleep(1) 
     fun +=1 
    ring("AirHorn") 

    times += 1 
    print("You have completed" + times + "Pomodoros.") 

但是,它只能通过一次;一旦它完成了5分钟的模块,控制台窗口关闭(我直接通过双击运行它,而不是通过终端)。

为什么会这样关闭?这是否与我使用while True:有关?

谢谢!

evamvid

+0

如果从控制台运行它,你会看到你很快为什么....以及在约5分钟 –

+0

看起来像它没有在这个“winsound.PlaySound(”% s.wav'%sound,winsound.SND_FILENAME)'行。你是否收到任何错误讯息? – sanooj

回答

1

在将来尝试从控制台运行它,所以你可以看到,当产生一个异常它所产生的回溯。

print("You have completed" + times + "Pomodoros.") 

您不能隐式连接int s和字符串。这会抛出TypeError,从而结束您的程序。

要解决:

print("You have completed " + str(times) + " Pomodoros.") # this works, and is ugly 

print("You have completed {} Pomodoros.".format(times)) # better.