python使用turtle库绘制时钟

yipeiwu_com6年前Python基础

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

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

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

使用5个turtle对象
1个turtle:绘制外表盘
3个turtle:模拟表针行为
1个turtle:输出表盘上文字

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

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

# -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 10:43:55 2018

@author: Administrator
"""

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",125)
  mkhand("minhand",130)
  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+second/60.0
  sechand.setheading(6*second)
  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.home()
  tracer(True)
  ontimer(tick,100)#100ms后继续调用tick

def main():
  tracer(False)
  init()
  setupclock(160)
  tracer(True)
  tick()
  mainloop()
main()

运行结果

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

相关文章

使用Python脚本将Bing的每日图片作为桌面的教程

微软最近出了个 必应bing 缤纷桌面,使用下来还是不错,可以每天更换Bing首页的北京作为壁纸,但是该软件有个不好的地方是,安装后桌面上会有一个搜索框出现,很是烦人,而且不能关掉。于是...

Python3.5装饰器原理及应用实例详解

Python3.5装饰器原理及应用实例详解

本文实例讲述了Python3.5装饰器原理及应用。分享给大家供大家参考,具体如下: 1、装饰器: (1)本质:装饰器的本质是函数,其基本语法都是用关键字def去定义的。 (2)功能:装饰...

Python字符串转换成浮点数函数分享

利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456 from functools import reduce def s...

python 实现手机自动拨打电话的方法(通话压力测试)

现在能用自动化实现的,尽量使用自动化程序去操作,代替人工去操作,更有效率。 今天说下用python结合adb命令去实现安卓手机端的通话压力测试。 #操作前先在设置里打开power键可...

python celery分布式任务队列的使用详解

python celery分布式任务队列的使用详解

一、Celery介绍和基本使用 Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理, 如果你的业务场景中需要用到异步任务,就可以考...