Python Turtle -时钟程序

Python Turtle -时钟程序_第1张图片

import turtle
from datetime import *

def skip(step):#抬起画笔,向前移动step长的距离
    turtle.penup()
    turtle.forward(step)
    turtle.pendown()

def getHand(name,length):#注册表针的形状
    turtle.reset()#注意重置
    skip(-length*0.1)
    turtle.begin_poly()
    turtle.forward(length*1.1)
    turtle.end_poly()
    handshape = turtle.get_poly()
    turtle.register_shape(name,handshape)

def Init():#初始化指针,打字writer
    global secHand,minHand,hurHand,writer
    turtle.mode('logo')
    getHand('secHand',135)
    getHand('minHand',125)
    getHand('hurHand',90)
    secHand = turtle.Turtle()
    secHand.shape('secHand')
    minHand = turtle.Turtle()
    minHand.shape('minHand')
    hurHand = turtle.Turtle()
    hurHand.shape('hurHand')  
    #设置指针尺寸
    secHand.shapesize(1,1,3)
    minHand.shapesize(1,1,5)
    hurHand.shapesize(1,1,9)
    for hand in secHand,minHand,hurHand:
        hand.color('dimgray')

    #创建打字手writer
    writer = turtle.Turtle()
    writer.hideturtle()
    writer.penup()

def DrawClock(radius):#绘制钟表的框框
    turtle.reset()
    turtle.pensize(7)
    for i in range(60):
        skip(radius)
        if i % 5 == 0:
            turtle.forward(20)
            skip(-radius-20)
            skip(radius+20)
            if i == 0:
                turtle.write(int(12),align='center',font=('微软雅黑',14))
            elif i == 30:
                skip(25)
                turtle.write(int(6),、
                align='center',font=('微软雅黑',14))
                skip(-25)
            elif (i == 25 or i == 35):
                skip(20)
                turtle.write(int(i/5),、
                align='center',font=('微软雅黑',14))
                skip(-20)
            else:
                turtle.write(int(i/5),、
                align='center',font=('微软雅黑',14))
            skip(-radius-20)#注意返回
        else:
            turtle.dot(5)
            skip(-radius)
        turtle.right(6)

def week(date_today):
    week=['星期一','星期二','星期三','星期四','星期五','星期六','星期日']
    return week[date_today.weekday()]

def date(date_today):
    return '{}-{}-{}'.format(date_today.year,date_today.month,date_today.day)
    
def TicTok():
    date_today = datetime.today()
    second = date_today.second + date_today.microsecond*0.000001
    minute = date_today.minute + second/60.0
    hour = date_today.hour + minute/60.0
    secHand.setheading(6*second)
    minHand.setheading(6*minute)
    hurHand.setheading(30*hour)

    turtle.tracer(False)
    writer.forward(65)
    writer.write(week(date_today),、
    align='center',font=('微软雅黑',14))
    writer.back(130)
    writer.write(date(date_today),、
    align='center',font=('微软雅黑',14))
    turtle.tracer(True)
    writer.home()#注意返回

    turtle.ontimer(TicTok,100)

def main():
    turtle.tracer(False)
    Init()
    DrawClock(160)
    turtle.tracer(True)
    TicTok()
    turtle.mainloop()

if __name__ == '__main__':
    main()

你可能感兴趣的:(Python基础,python)