python 海龟画图时钟案例


效果图片

 

 

环境:python3.9.6

 

源代码:

#! /usr/bin/env python 
# -*- coding:utf-8 -*-
import turtle
import datetime

def skip(step): #画笔移动指定的距离

turtle.penup()
turtle.forward(step)
turtle.pendown()

pass

def set_up(radius): #表盘绘制 radius 表盘的半径

turtle.reset() #删除图形归位
turtle.pensize(7)
turtle.hideturtle() # 隐藏箭头

for i in range(60): #循环60次 60个刻度
skip(radius) #移动到半径处
if i%5 == 0: #若能被5整除 就画短线
turtle.forward(20)
skip(-radius-20) #返回圆心
else:
turtle.dot(5) #画点
skip(-radius) #返回圆心
turtle.right(6) #向右旋转6度

pass

def make_hand(name,len):# 创建指针方法

turtle.reset() #删除图形归位
skip(-0.1*len) #抬笔移动指定距离
turtle.begin_poly() #记录多边形
turtle.forward(1.1*len) #绘制指定长度的指针
turtle.end_poly() # 停止记录多边形

#注册多边形状
turtle.register_shape(name,turtle.get_poly())

pass

def init(): # 初始化指针

global secHand, minHand, hurHand, printer

turtle.mode("logo") # 重置Turtle指向上

#建立 时针 分针 秒针
make_hand("secHand",140) #秒针图形
make_hand("minHand", 125) #分针图形
make_hand("hurHand", 70) #秒针图形

secHand = turtle.Turtle() # 创建秒针turtle对象
secHand.shape("secHand") #创建指定秒针名称的形状

minHand = turtle.Turtle() # 创建分针turtle对象
minHand.shape("minHand") # 创建指定分针名称的形状

hurHand = turtle.Turtle() # 创建时针turtle对象
hurHand.shape("hurHand") # 创建指定时针名称的形状

for hand in secHand, minHand, hurHand: #遍历3个指针
hand.shapesize(1, 1, 5) # 调整3根指针的粗细
hand.speed(0) # 设置速度为最快

printer = turtle.Turtle() # 创建绘制文字的Turtle对象
printer.hideturtle() # 隐藏箭头
printer.penup() # 抬笔

pass

def week(t):# 获取星期的方法
week = ["星期一","星期二","星期三","星期四","星期五","星期六","星期天"]
return week[t.weekday()]

def day(t):
return "%s年%d月%d日"%(t.year,t.month,t.day)


def tick(): #移动指针的方法

t = datetime.datetime.today() #获取当前的时间

second = t.second + t.microsecond * 0.000001 # 计算移动的秒
minute = t.minute + second / 60 # 计算移动的分
hour = t.hour + minute / 60 # 计算移动的小时

secHand.setheading(6 * second) # 设置秒针的角度
minHand.setheading(6 * minute) # 设置分针的角度
hurHand.setheading(30 * hour) # 设置时针的角度

turtle.tracer(False) # 关闭绘画效果
printer.forward(65) # 向上移动65
# 绘制星期
printer.write(week(t), align="center", font=("Courier", 14, "bold"))
printer.back(130) # 倒退130
# 绘制年月日
printer.write(day(t),align="center", font=("Courier", 14, "bold"))
printer.home() # 归位
turtle.tracer(True) # 开启绘画效果
turtle.ontimer(tick(),100) # 10毫秒后调用tick()方法

pass

def main():

turtle.tracer(False) # 关闭绘画效果
init() #初始化指针
set_up(170) #初始化表盘
turtle.tracer(True) # 开始绘画效果
tick()
turtle.done()
turtle.mainloop() # 不关闭窗体

pass

if __name__ == '__main__':
main()


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM