1. 程式人生 > >【Python基礎】1.4.5 Turtle例項——用Python實現時鐘顯示

【Python基礎】1.4.5 Turtle例項——用Python實現時鐘顯示

語言:Python
IDE:Python.IDE

  1. 編寫時鐘程式,要求根據時間動態更新
    這裡寫圖片描述

  2. 程式碼思路
    需求:5個Turtle物件, 1個繪製外表盤+3個模擬表上針+1個輸出文字
    Step1:建立Turtle物件並初始化
    Step2:靜態錶盤繪製
    Step3:根據時鐘更新錶針位置與時間資訊
    基本庫:Turtle、datetime

  3. 程式碼段

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() #註冊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 = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"] 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()