python使用turtle庫繪制時鐘
Python函數(shù)庫眾多,而且在不斷更新,所以學習這些函數(shù)庫最有效的方法,就是閱讀Python官方文檔。同時借助Google和百度。
本文介紹的turtle庫對應的官方文檔地址
繪制動態(tài)鐘表的基本思路如下(面向對象的編程):
使用5個turtle對象
1個turtle:繪制外表盤
3個turtle:模擬表針行為
1個turtle:輸出表盤上文字
根據(jù)實時時間使用ontimer()函數(shù)更新表盤畫面,顯示效果如下:
相關函數(shù)的使用在程序中進行了詳細的注釋,代碼如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 10:43:55 2018
@author: Administrator
"""
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()
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ài)顯示
t=datetime.today()
second=t.second+t.microsecond*0.000001
minute=t.minute+second/60.0
hour=t.hour+second/60.0
sechand.setheading(6*second)
minhand.setheading(6*minute)
hurhand.setheading(30*hour)
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后繼續(xù)調用tick
def main():
tracer(False)
init()
setupclock(160)
tracer(True)
tick()
mainloop()
main()
運行結果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python虛擬環(huán)境創(chuàng)建的兩種方法
本文主要介紹了python虛擬環(huán)境創(chuàng)建的兩種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05
PyTorch實現(xiàn)聯(lián)邦學習的基本算法FedAvg
這篇文章主要為大家介紹了PyTorch實現(xiàn)聯(lián)邦學習的基本算法FedAvg,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
Pycharm pyuic5實現(xiàn)將ui文件轉為py文件,讓UI界面成功顯示
這篇文章主要介紹了Pycharm pyuic5實現(xiàn)將ui文件轉為py文件,讓UI界面成功顯示,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
用Python編寫一個簡單的FUSE文件系統(tǒng)的教程
這篇文章主要介紹了用Python編寫一個簡單的FUSE文件系統(tǒng)的教程,對于數(shù)據(jù)的備份很有幫助,需要的朋友可以參考下2015-04-04
利用Python將Excel快速轉換成HTML的代碼實現(xiàn)
在日常的辦公和數(shù)據(jù)處理任務中,Excel文件因其強大的表格數(shù)據(jù)管理能力而備受歡迎,然而,在某些情況下,我們可能需要將Excel文件轉換成HTML格式,以便在網(wǎng)頁上展示或進行進一步的數(shù)據(jù)處理,本文將介紹如何利用Python將Excel文件快速轉換成HTML,并提供具體的代碼示例和案例2024-12-12
Python?按規(guī)則解析并替換字符串中的變量及函數(shù)(示例代碼)
這篇文章主要介紹了Python?按規(guī)則解析并替換字符串中的變量及函數(shù),本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-11-11

