功能介绍
用户输入一个整分钟,启动计时器,他就会倒数到零,并且响铃声。
该功能目前不接受带有小数的分钟输入比如1.2分钟,2.8分钟等。
该功能使用海龟库显示倒计时效果,使用pygame库来实现音乐播放效果,整体原理很简单,我就把代码放在这里了
import time
from turtle import *
import pygame
pygame.init()
def show_time_screen(total_min: int): # parameter in minutes
if total_min < 1:
print("no time!")
return
if not isinstance(total_min, int):
print("invalid time input")
total_min -= 1
sc = 60 # second
sz = 160 # size of a character on the screen
dev = 0 # deviation in counting
# go to correct position
speed(0)
penup()
goto(-sz * 2, -sz / 2)
while total_min > -1:
#reduce deviation
if dev < 1:
intv = 1 - dev
else:
intv = 0 # set time slice to zero for deviation reduction
time.sleep(intv)
start = time.perf_counter()
sc -= 1
# effect:1:09 instead of 1:9
if 0 <= sc < 10:
str_sc = "0" + str(sc)
else:
str_sc = str(sc)
# clear the screen
clear()
write(str(total_min) + ":" + str_sc, font=("arial", sz, "normal"))
# reset second (one minute has passed)
if sc <= 0:
total_min -= 1
sc = 60
end = time.perf_counter()
dev = round(end - start, 8) # time taken for program to count (deviation)
pygame.mixer.Sound("clock.wav").play()
show_time_screen(1)
pygame.quit()
done()
效果图