效果圖片

環境: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()
