绘制动态钟表的基本思路如下(面向对象的编程):
使用5个turtle对象
1个turtle:绘制外表盘
3个turtle:模拟表针行为
1个turtle:输出表盘上文字
根据实时时间使用ontimer()函数更新表盘画面,显示效果如下:
1 from turtle import * 2 from datetime import * 3 4 def Skip(step):#跨越函数,通过penup()和pendown()实现step像素的跨越操作 5 penup() 6 forward(step) 7 pendown() 8 9 def mkHand(name, length):#定义表针函数#注册Turtle形状,建立表针Turtle 10 11 reset()#清空当前窗口,并重置位置等信息为默认值 12 Skip(-length*0.1)#通过skip()设置中心点 13 begin_poly()# 14 forward(length*1.1)#完成绘制几何形状 15 end_poly()# 16 handForm = get_poly()#通过get_plpy()将该形状赋给变量handForm,其类型为shape 17 register_shape(name, handForm) 18 19 def Init():#初始化函数,建立三个指表针turtle对象,和文本turtle对象并对其进行初始化 20 global secHand, minHand, hurHand, printer#四个turtle对象,都通过global声明为全局对象 21 mode("logo")# 重置Turtle指向北 22 #建立三个表针Turtle并初始化 23 mkHand("secHand", 125) 24 mkHand("minHand", 130) 25 mkHand("hurHand", 90) 26 secHand = Turtle() 27 secHand.shape("secHand") 28 minHand = Turtle() 29 minHand.shape("minHand") 30 hurHand = Turtle() 31 hurHand.shape("hurHand") 32 for hand in secHand, minHand, hurHand:#对三个对象进行初始化 33 hand.shapesize(1, 1, 3) 34 hand.speed(0) 35 #建立输出文字Turtle 36 printer = Turtle() 37 printer.hideturtle() 38 printer.penup() 39 40 def SetupClock(radius):#表盘绘制函数 41 #建立表的外框 42 reset() 43 pensize(7) 44 for i in range(60):#绘制表盘刻度,每五个刻度画一个短线断,其余为小圆点 45 Skip(radius) 46 if i % 5 == 0: 47 forward(20) 48 Skip(-radius-20) 49 else: 50 dot(5) 51 Skip(-radius) 52 right(6) 53 54 def Week(t): 55 week = ["星期一", "星期二", "星期三", 56 "星期四", "星期五", "星期六", "星期日"] 57 return week[t.weekday()] 58 59 def Date(t): 60 y = t.year 61 m = t.month 62 d = t.day 63 return "%s %d %d" % (y, m, d) 64 65 def Tick():#更新时钟函数 66 #绘制表针的动态显示 67 t = datetime.today()#获取当前时间 68 #以下分别计算带小数的时分秒值 69 second = t.second + t.microsecond*0.000001 70 minute = t.minute + second/60.0 71 hour = t.hour + minute/60.0 72 secHand.setheading(6*second) 73 minHand.setheading(6*minute) 74 hurHand.setheading(30*hour) 75 76 tracer(False) 77 printer.forward(65) 78 printer.write(Week(t), align="center", 79 font=("Courier", 14, "bold")) 80 printer.back(130) 81 printer.write(Date(t), align="center", 82 font=("Courier", 14, "bold")) 83 printer.home()#将turtle对象元素归位到原点 84 tracer(True) 85 86 ontimer(Tick, 100)#100ms后继续调用tick 87 88 def main(): 89 tracer(False)#控制刷新,false表示动画关闭,绘制完成后一次性刷新 90 Init() 91 SetupClock(160) 92 tracer(True)#True参数,恢复动画刷新 93 Tick() 94 mainloop() 95 96 if __name__ == "__main__": 97 main()