既然是画时钟,那必不可少的就是turtle和datetime模块了,以上都是自带模块不需要下载
首先我们让钟能悬空移动
def move(distance):
turtle.penup()
turtle.forward(distance)
turtle.pendown()
再创建表针turtle
def createHand(name, length):
turtle.reset()
move(-length * 0.01)
turtle.begin_poly()
turtle.forward(length * 1.01)
turtle.end_poly()
hand = turtle.get_poly()
turtle.register_shape(name, hand)
最后再创建时钟
def createClock(radius):
turtle.reset()
turtle.pensize(7)
for i in range(60):
move(radius)
if i % 5 == 0:
turtle.forward(20)
move(-radius-20)
else:
turtle.dot(5)
move(-radius)
turtle.right(6)
至此主体部分差不多完成了,现在我们要为这个时钟添加细节,例如获取今天的日期;今天是星期几;动态显示表针之类的.
最后我们来定义运行时钟这个函数
def start():
# 不显示绘制时钟的过程
turtle.tracer(False)
turtle.mode('logo')
createHand('second_hand', 150)
createHand('minute_hand', 125)
createHand('hour_hand', 85)
# 秒, 分, 时
second_hand = turtle.Turtle()
second_hand.shape('second_hand')
minute_hand = turtle.Turtle()
minute_hand.shape('minute_hand')
hour_hand = turtle.Turtle()
hour_hand.shape('hour_hand')
for hand in [second_hand, minute_hand, hour_hand]:
hand.shapesize(1, 1, 3)
hand.speed(0)
# 用于打印日期等文字
printer = turtle.Turtle()
printer.hideturtle()
printer.penup()
createClock(160)
# 开始显示轨迹
turtle.tracer(True)
startTick(second_hand, minute_hand, hour_hand, printer)
turtle.mainloop()
我们以主窗口来运行它
if __name__ == '__main__':
start()
我把源码放在了下面,有需要的自取,记得三联
|