Python时钟代码解析

发布于:2022-12-03 ⋅ 阅读:(1003) ⋅ 点赞:(0)

要用Python制作一个时钟,首先需要将时钟的轮廓画出来。

import turtle as t

import datetime as d

这两行代码就不必解析了

def skip(step):

    t.penup()

    t.forward(step)

    t.pendown()

此处的函数定义的是抬笔并准备要开始从0点开始画半圆的闹钟

def drawClock(radius):

    t.speed(0)

    t.mode("logo")

    t.hideturtle()

    t.pensize(7)

    t.home()

    for j in range(60):

        skip(radius)

        if(j % 5 == 0):

            t.forward(20)

            skip(-radius-20)

        else:

            t.dot(5)

            skip(-radius)

        t.right(6)

这里已经就开始了绘制表盘了,t.mode(logo)就是设定画笔(turtle)的形状,并且用hideturtle隐藏画笔,最终t.home()也就是回到了原点。接下来进行循环。

重点:%是取余,==是等于号

这个意思就是说如果能整除5(j除以5没有余数时,画出刻度,也就是钟表上1,2,3……12的刻度),否则(else)就画点,一共需要画出60个,360度,所以需要右转6度。

def makePoint(pointName,len):

    t.penup()

    t.home()

    t.begin_poly()

    t.back(0.1*len)

    t.forward(len*1.1)

    t.end_poly()

    poly=t.get_poly()

    t.register_shape(pointName,poly)

makePoint("hour",100)

这边定义了时针,分针,秒针所在的点。

重点:t.register_shape(pointName,poly)注册了一个图形,get_poly获得多边形的角的点数

def drawpoint():

    global hourPoint,minPoint,secPoint,fontWriter

    makePoint("hourPoint",100)

    makePoint("minPoint",120)

    makePoint("secPoint",140)

    hourPoint=t.Pen()

    hourPoint.shape("hourPoint")

    hourPoint.shapesize(1,1,6)

    minPoint=t.Pen()

    minPoint.shape("minPoint")

    minPoint.shapesize(1,1,4)

    secPoint=t.Pen()

    secPoint.shape("secPoint")

    secPoint.pencolor('red')

    fontWriter=t.Pen()

    fontWriter.pencolor('gray')

    fontWriter.hideturtle()

这里的global就是全局变量,每一个=t.pen()就是设一个画笔(时针,分针,秒针)

def getWeek(weekday):

    weekName=['星期一','星期二','星期三','星期四','星期五','星期六','星期日']

    return weekName[weekday]

需要得到今天是周几(星期一,星期二……星期日)

def getDate(year,month,day):

   return "%s-%s-%s" % (year,month,day)

重点:%在这里是占位符

def getRealtime():

    curr=d.datetime.now()

    curr_year=curr.year

    curr_month=curr.month

    curr_day=curr.day

    curr_hour=curr.hour

    curr_minute=curr.minute

    curr_second=curr.second

    curr_weekday=curr.weekday()

    t.tracer(False)

    secPoint.setheading(360/60*curr_second)

    minPoint.setheading(360/60*curr_minute)

    hourPoint.setheading(360/12*curr_hour+30/60*curr_minute)

    fontWriter.clear()

    fontWriter.home()

    fontWriter.penup()

   fontWriter.forward(80)

    fontWriter.write(getWeek(curr_weekday),align="center",font=("Courier",14,"bold"))

    fontWriter.forward(-160)

    fontWriter.write(getDate(curr_year,curr_month,curr_day),align="center",font=("Courier",14,"bold"))

    t.tracer(True)

    print(curr_second)

    t.ontimer(getRealtime,1000)

需要知道电脑的时间,所以要curr=d.datetime.now(),第11~13行是时分秒之间的转换,第17~20行可以画出“星期几”的字样和“几几年几月几日”的字样。最后一行的1000是1000毫秒,也就是1秒钟(秒针)。

def main():

    t.tracer(False)

    drawClock(160)

    drawpoint()

    getRealtime()

    t.tracer(True)

    t.mainloop()

main()

最后将所有的定义的函数汇集到一起,全部调用。

结果示意:

 

本文含有隐藏内容,请 开通VIP 后查看