首页 > IT职业 > IT图书 > 如何用Python实现简单的计时器

开发工具
Python版本:3.6.4
相关模块:
SimpleGUICS2Pygame模块。
环境搭建
安装Python并添加到环境变量,pip安装需要的相关模块即可。
原理简介
1、首先创建主界面和一个计时器。
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()
2、t每计数十次为一秒,因此将t转换为分秒格式的代码。
''' 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)
3、实现开始计时,结束计时,清空当前计时和将计时绘制在主界面上了。
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')
以上就是如何用Python实现简单计时器的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文转载于博客园,如有侵犯联系作者修改。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4560/viewspace-2828615/ ,如需转载,请注明出处,否则将追究法律责任。