Python实现模拟时钟代码推荐
语言:Python
IDE:Python.IDE
一、编写时钟程序,要求根据时间动态更新
代码思路【关注后私信小编 PDF领取十套电子文档书籍】
- 需求:5个Turtle对象, 1个绘制外表盘+3个模拟表上针+1个输出文字
- Step1:建立Turtle对象并初始化
- Step2:静态表盘绘制
- Step3:根据时钟更新表针位置与时间信息
基本库:Turtle、datetime
效果图
代码也很简单
from turtle import * from datetime import * import time,sys,os 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() #注册Turtle形状命令register_shape(name,shape=None) 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 = ["Python学习群:516107834", "Python学习群:516107834", "Python学习群:516107834", "Python学习群:516107834", "Python学习群:516107834", "Python学习群:516107834", "Python学习群:516107834"] 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) minHand.setheading(6*minute) hurHand.setheading(30*hour) #介入Tracer函数以控制刷新速度 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() if __name__ == "__main__": main()
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16