python小程序—即时动态时钟
1.完整代码:
# coding=UTF-8
from turtle import *
from datetime import *
def Skip(step): #建立表的外框
penup()
forward(step)
pendown()
def mkHand(name,length): #注册turtle形状,建立表针turtle
reset()
Skip(-length*0.1)
begin_poly()
forward(length*1.1)
end_poly()
handForm = get_poly()
register_shape(name,handForm)
def Init():
global secHand,minHand,hurHand,printer
mode("logo") #重置turtle指向北
mkHand("secHand",125) #建立三个表针并初始化
mkHand("minHand",130)
mkHand("hurHand",90)
secHand = Turtle()
secHand.shape("secHand")
minHand = Turtle()
minHand.shape("minHand")
hurHand = Turtle()
hurHand.shape("hurHand")
for hand in secHand,minHand,hurHand:
hand.shapesize(1,1,3)
hand.speed(0)
printer = Turtle() #建立输出文字turtle
printer.hideturtle()
printer.penup()
def SetupClock(radius): #建立表外框
reset()
pensize(7)
for i in range(60):
Skip(radius)
if i % 5 == 0:
forward(20)
Skip(-radius-20)
else:
dot(5)
Skip(-radius)
right(6)
def Week(t):
week = ["Mon", "Tues", "Wed","Thur", "Fri", "Sat", "Sun"]
return week[t.weekday()]
def Date(t):
y = t.year
m = t.month
d = t.day
return "%s %d %d" % (y, m, d)
def Tick():
t = datetime.today()
second = t.second + t.microsecond * 0.000001
minute = t.minute + second/60.0
hour = t.hour + minute/60.0
secHand.setheading(6*second)
minHand.setheading(6*minute)
hurHand.setheading(30*hour)
tracer(False)
printer.forward(65)
printer.write(Week(t),align="center",font=("Courier",14,"bold"))
printer.back(130)
printer.write(Date(t),align="center",font=("Courier",14,"bold"))
printer.home()
tracer(True)
ontimer(Tick,100) #100ms后继续调用tick
def main():
tracer(False)
Init()
SetupClock(160)
tracer(True)
Tick()
mainloop()
if __name__ == "__main__":
main()
- 运行结果截图
- 程序解读
1、思路
需求:5个Turtle对象, 1个绘制外表盘+1个输出文字++3个模拟表上针
Step1:建立5个Turtle对象并初始化 (表盘绘制和文本输出对象是turtle常见的对象方式;turtle的外观shape就是指针形状,在每一时刻以轴心为圆心旋转了一定角度)
Step2:静态表盘绘制
Step3:根据时钟更新表针位置与时间信息
基本库:Turtle、datetime
2、代码
(1)from turtle import *
Turtle库——Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟(画笔),在一个横轴为x、纵轴为y的坐标系(画布),根据一组函数指令的控制,在平面坐标系中移动,从而在它爬行的路径上绘制了图形。
操纵海龟绘图有3种命令:
运动命令