前言
Python函數庫眾多,而且在不斷更新,所以學習這些函數庫最有效的方法,就是閱讀Python官方文檔。同時借助Google和百度。
turtle庫中文文檔:
https://docs.python.org/zh-cn/3/library/turtle.html
開發工具
Python版本:3.6.4
相關模塊:
turtle庫等python自帶的模塊。
環境搭建
安裝Python並添加到環境變量即可。
原理介紹
利用Turtle庫制作一個簡易時鍾可以分為三步。
第一步:初始化
第二步:創建時鍾
第三步,動態顯示時鍾
初始化需要定義時針分針秒針以及打印文字所需的turtle對象,共四個。其中時針分針秒針這三個turtle對象的定義方式如下:
createHand('second_hand', 150)
createHand('minute_hand', 125)
createHand('hour_hand', 85)
# 秒, 分, 時
second_hand = turtle.Turtle()
second_hand.shape('second_hand')
minute_hand = turtle.Turtle()
minute_hand.shape('minute_hand')
hour_hand = turtle.Turtle()
hour_hand.shape('hour_hand')
for hand in [second_hand, minute_hand, hour_hand]:
hand.shapesize(1, 1, 3)
hand.speed(0)
其中createHand函數用於創建表針(定義形狀長度等),其代碼實現如下:
'''創建表針turtle'''
def createHand(name, length):
turtle.reset()
move(-length * 0.01)
turtle.begin_poly()
turtle.forward(length * 1.01)
turtle.end_poly()
hand = turtle.get_poly()
turtle.register_shape(name, hand)
然后定義用於打印文字的turtle對象:
# 用於打印日期等文字
printer = turtle.Turtle()
printer.hideturtle()
printer.penup()
createClock(160)
即繪制時鍾。其代碼實現如下:
'''創建時鍾'''
def createClock(radius):
turtle.reset()
turtle.pensize(7)
for i in range(60):
move(radius)
if i % 5 == 0:
turtle.forward(20)
move(-radius-20)
else:
turtle.dot(5)
move(-radius)
turtle.right(6)
為了便於大家理解代碼,錄了一小段這部分代碼運行時的效果圖:
動態顯示時鍾的源代碼如下:
'''動態顯示表針'''
def startTick(second_hand, minute_hand, hour_hand, printer):
today = datetime.datetime.today()
second = today.second + today.microsecond * 1e-6
minute = today.minute + second / 60.
hour = (today.hour + minute / 60) % 12
# 設置朝向
second_hand.setheading(6 * second)
minute_hand.setheading(6 * minute)
hour_hand.setheading(12 * hour)
turtle.tracer(False)
printer.forward(65)
printer.write(getWeekday(today), align='center', font=("Courier", 14, "bold"))
printer.forward(120)
printer.write('12', align='center', font=("Courier", 14, "bold"))
printer.back(250)
printer.write(getDate(today), align='center', font=("Courier", 14, "bold"))
printer.back(145)
printer.write('6', align='center', font=("Courier", 14, "bold"))
printer.home()
printer.right(92.5)
printer.forward(200)
printer.write('3', align='center', font=("Courier", 14, "bold"))
printer.left(2.5)
printer.back(400)
printer.write('9', align='center', font=("Courier", 14, "bold"))
printer.home()
turtle.tracer(True)
# 100ms調用一次
turtle.ontimer(lambda: startTick(second_hand, minute_hand, hour_hand, printer), 100)
即利用datetime庫獲取當前的日期與時間,將日期打印在鍾表上下兩側,並根據時間調整表針角度,並標明時鍾上的點所代表的數字。
注意:為了運行代碼時直接呈現出時鍾,第一第二步中的代碼運行時均設置tracker為False。僅在第三步中設置tracker為True。
文章到這里就結束了,感謝你的觀看,關注我每天分享Python小工具系列,下篇文章分享簡易音樂播放器