为什么这个脚本不循环/只运行一次?

0 投票
1 回答
770 浏览
提问于 2025-04-17 22:04

这是我写的一个简单的番茄钟计时器。理论上,它可以无限运行,交替进行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

1 个回答

1

将来可以尝试在控制台中运行它,这样你就能看到当出现错误时生成的错误追踪信息。

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

你不能直接把数字(int)和字符串拼接在一起。这会导致一个叫做TypeError的错误,从而让你的程序停止运行。

要解决这个问题:

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

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

撰写回答