python实现定时器

该代码实现了一个计时器的功能,使用SimpleGUICS2Pygame库来创建GUI界面。以下是代码中各函数的功能:

  1. Convert(t):将时间t(单位为0.1秒)转换为<A:BC.D>格式的字符串。

  2. Start():开始计时,如果计时器没有正在运行,则启动计时器。

  3. Stop():停止计时,停止计时器,并将绘制时间的颜色改为红色。

  4. Clear():清空计时器,将时间归零并停止计时器,并将绘制时间的颜色改为白色。

  5. timerHandler():计时器处理函数,每0.1秒执行一次,将时间t加1。

  6. drawHandler(canvas):绘制函数,将转换后的时间字符串绘制到canvas上。

  7. main():主函数,创建GUI界面和计时器,并启动GUI界面。

代码中全局变量t记录时间(单位为0.1秒),color记录绘制时间的颜色,timer是计时器。通过设置计时器的运行间隔为100ms,即每10次计时器事件为一秒。在GUI界面中添加三个按钮,分别为开始计时、停止计时和清空。通过SimpleGUICS2Pygame库提供的函数创建GUI界面并注册事件处理函数,主函数中调用create_frame()函数创建GUI界面,然后创建计时器和按钮,并启动GUI界面。

 

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
'''
Function:
	将时间转为<A:BC.D>格式
'''
def Convert(t):
	D = t % 10
	# 十位
	B = (t // 100) % 6
	# 个位
	C = (t // 10) % 10
	# 分钟
	A = t // 600
	return str(A) + ':' + str(B) + str(C) + '.' + str(D)


'''
Function:
	开始计时
'''
def Start():
	global timer, color
	color = 'white'
	if not timer.is_running():
		timer.start()


'''
Function:
	停止计时
'''
def Stop():
	global timer, color
	timer.stop()
	color = 'red'


'''
Function:
	清空
'''
def Clear():
	global t, timer, color
	timer.stop()
	t = 0
	color = 'white'


'''
Function:
	计时器
'''
def timerHandler():
	global t
	t += 1


'''
Function:
	绘制时间
'''
def drawHandler(canvas):
	t_convert = Convert(t)
	canvas.draw_text(t_convert, (25, 120), 60, color, 'serif')


'''
Function:
	主函数
'''
def main():
	global t, color
	t = 0
	color = 'white'
	frame = simplegui.create_frame('Timer', 200, 200, 150)
	# 1000 / 100 = 10, 即t自加10次为一秒
	global timer
	timer = simplegui.create_timer(100, timerHandler)
	frame.set_draw_handler(drawHandler)
	button_start = frame.add_button('Start', Start, 150)
	button_stop = frame.add_button('Stop', Stop, 150)
	button_clear = frame.add_button('Clear', Clear, 150)
	frame.start()


if __name__ == '__main__':
	main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忧伤的玩不起

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值