前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用Python画一个实时的时钟

用Python画一个实时的时钟

作者头像
算法与编程之美
发布2023-08-22 14:30:20
2380
发布2023-08-22 14:30:20
举报
文章被收录于专栏:算法与编程之美

1 问题

如何用Python画一个实时的时钟?

2 方法

(1)安装turtle模块,turtle库是python的标准库之一,属于入门级的图形绘制函数库,通过它可以实现图像的生成。

(2)使用turtle库画图的特性画出时钟。

(3)最后通过自定义shape的方法完成绘制。

代码清单 1

import turtle as timport datetime as ddef skip(step): t.penup() t.forward(step) t.pendown()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)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) 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()def getWeekName(weekday): weekName = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'] return weekName[weekday]def getDate(year, month, day): return "%s-%s-%s" % (year, month, day)def realTime(): 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(getWeekName(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(realTime, 100) def main(): t.tracer(False) drawClock(160) drawPoint() realTime() t.tracer(True) t.mainloop()if __name__ == '__main__': main()

3 结语

针对制作简易的实时时钟问题,经过测试,证明可以通过使用turtle模块实现。之后还可以优化:例如加入每个小点所对应的具体数字,以及该天所对应的天气,不断的完善该程序。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-07-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 算法与编程之美 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档