该代码实现了一个计时器的功能,使用SimpleGUICS2Pygame库来创建GUI界面。以下是代码中各函数的功能:
-
Convert(t):将时间t(单位为0.1秒)转换为<A:BC.D>格式的字符串。
-
Start():开始计时,如果计时器没有正在运行,则启动计时器。
-
Stop():停止计时,停止计时器,并将绘制时间的颜色改为红色。
-
Clear():清空计时器,将时间归零并停止计时器,并将绘制时间的颜色改为白色。
-
timerHandler():计时器处理函数,每0.1秒执行一次,将时间t加1。
-
drawHandler(canvas):绘制函数,将转换后的时间字符串绘制到canvas上。
-
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()