用Python画了一个钟
作者:互联网
用python画了一个钟
代码如下
import turtle as t
import datetime as d
import math
def skip(step):
# 跳跃给定的距离
t.penup()
t.fd(step)
t.pendown()
# 时钟的头部
def clock_hand():
t.bgcolor("yellow")
t.pensize(5)
t.color("black")
t.right(90)
t.color("black", 'green')
t.begin_fill()
t.circle(50, 360)
t.end_fill()
t.up()
t.left(90)
t.fd(60)
t.left(90)
t.up()
t.fd(20)
t.down()
t.color("black")
t.dot(20) # 画一个点
t.write("溪山看未足,还听暮楼钟。", align="center", font=("演示悠然小楷", 35, "bold"))
t.up()
t.fd(-40)
t.down()
t.color("black")
t.dot(20) # 画一个点
t.up()
t.fd(20)
t.right(90)
t.fd(-30)
t.down()
t.color("red")
t.dot(20) # 画一个点
t.up()
t.fd(-30)
def setup_clock(radius):
'''
建立钟表外框
'''
t.reset()
# 设置画笔的粗细
t.pensize(8)
a = 0
for i in range(60):
# 在距离圆心为r的位置落笔
skip(radius)
if i % 5 == 0:
# 画一条直线
t.color("black")
t.write(a, align="center", font=("演示悠然小楷", 30, "bold"))
a = a+1
t.color("red")
t.forward(20)
if i == 0:
clock_hand()
if i == 30:
t.up()
t.fd(-60)
t.down()
t.color("blue")
t.write("时钟", align="center", font=("演示悠然小楷", 30, "bold"))
t.up()
t.fd(60)
skip(-radius - 20)
else:
t.color("green")
t.dot(5) # 画一个点
skip(-radius)
t.right(6)
def make_hand(name, length):
'''
注册turtle的形状,建立一个名字为name的形状
:param name:
:param length:
:return:
'''
t.reset()
skip(-length * 0.1)
# 开始记录多变形的定点
t.begin_poly()
t.forward(length * 1.1)
t.end_poly()
# 返回形状
handForm = t.get_poly()
# 注册形状,名为name
t.register_shape(name, handForm)
def init():
global secHand, minHand, hourHand, printer
# 设置指针的长度
values = (
('secHand', 140),
('minHand', 125),
('hourHand', 90)
)
# 重置turtle自增朝北
t.mode('logo')
# 建立三个表示指针的turtle
hands = []
for name, length in values:
hand = t.Turtle()
make_hand(name, length)
hand.shape(name)
hand.shapesize(1, 1, 3)
hand.speed(0)
hands.append(hand)
secHand, minHand, hourHand = hands
printer = t.Turtle()
printer.hideturtle()
printer.penup()
def draw_hand(time):
second = time.second + time.microsecond * 0.000001
minute = time.minute + time.second / 60.0
hour = time.hour + time.minute / 60.0
secHand.setheading(second * 6)
minHand.setheading(minute * 6)
hourHand.setheading(hour * 30)
def week(time):
week = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]
return week[time.weekday()]
def day(time):
return f'{time.year} {time.month} {time.day}'
def name():
return "为了理想"
def draw_date(time):
t.tracer(False)
printer.forward(70)
printer.write(week(time), align="center", font=("演示悠然小楷", 18, 'bold'))
printer.back(130)
printer.write(day(time), align='center', font=('演示悠然小楷', 14, 'bold'))
printer.forward(30)
printer.write(name(), align="right", font=('演示悠然小楷', 18, 'bold'))
printer.home()
t.tracer(True)
def tick():
time = d.datetime.today()
draw_hand(time)
draw_date(time)
t.ontimer(tick, 200)
if __name__ == "__main__":
# 关闭绘画跟踪,可以用于加速绘图
t.tracer(False)
init()
setup_clock(200)
t.tracer(True)
tick()
t.hideturtle()
t.done()
运行结果如下
我用的字体电脑一般不会自带,我用的是小楷字体。比较喜欢这种字体。看起来很舒服。
标签:printer,name,Python,hand,一个,color,time,def 来源: https://blog.csdn.net/weixin_47994845/article/details/121043478