python使用Turtle库绘制动态钟表

yipeiwu_com7年前Python基础

Python函数库众多,而且在不断更新,所以学习这些函数库最有效的方法,就是阅读Python官方文档。同时借助Google和百度。

本文介绍的turtle库对应的官方文档地址

绘制动态钟表的基本思路如下(面向对象的编程):

使用5个turtle对象

1个turtle:绘制外表盘

3个turtle:模拟表针行为

1个turtle:输出表盘上文字

根据实时时间使用ontimer()函数更新表盘画面,显示效果如下:

相关函数的使用在程序中进行了详细的注释,代码如下:

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指向北
 #建立三个表针Turtle并初始化
 mkHand("secHand", 135)
 mkHand("minHand", 110)
 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)
 #建立输出文字Turtle
 printer = 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 = ["星期一", "星期二", "星期三",
   "星期四", "星期五", "星期六", "星期日"]
 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) #设置朝向,每秒转动6度
 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.back(50)
 printer.write("i_chaoren", align="center",
     font=("Courier", 14, "bold"))
 printer.home()
 tracer(True)
 
 ontimer(Tick, 1000)#1000ms后继续调用tick
 
def main():
 tracer(False) #使多个绘制对象同时显示
 Init()
 SetupClock(160)
 tracer(True)
 Tick()
 mainloop()
 
if __name__ == "__main__":  
 main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

基于python 处理中文路径的终极解决方法

1 、据说python3就没有这个问题了 2 、u'字符串' 代表是unicode格式的数据,路径最好写成这个格式,别直接跟字符串'字符串'这类数据相加,相加之后type就是str,这样...

phpsir 开发 一个检测百度关键字网站排名的python 程序

源码如下 :保存成utf-8 bd.py 文件 复制代码 代码如下:#!/usr/bin/env python # -*- coding: utf-8 -*- import sys im...

python 通过logging写入日志到文件和控制台的实例

如下所示: import logging # 创建一个logger logger = logging.getLogger('mylogger') logger.setLev...

Python wxPython库Core组件BoxSizer用法示例

Python wxPython库Core组件BoxSizer用法示例

本文实例讲述了Python wxPython库Core组件BoxSizer用法。分享给大家供大家参考,具体如下: wx.BoxSizer: box = wx.BoxSizer(int...

Python基于matplotlib绘制栈式直方图的方法示例

Python基于matplotlib绘制栈式直方图的方法示例

本文实例讲述了Python基于matplotlib绘制栈式直方图的方法。分享给大家供大家参考,具体如下: 平时我们只对一组数据做直方图统计,这样我们只要直接画直方图就可以了。 但有时候我...