首頁 > 軟體

基於Python製作三款起床鬧鐘的範例程式碼

2022-05-14 13:01:50

導語

叮叮叮,我們要按時長大

我是你們的木子同學!噹噹噹當——隆重出場,撒花撒花~

嗨!大家有沒有生物鐘不準時的時候,是不是每到休息日或者長假就會經常要倒時差?

每天上班最痛苦的事情就是早起早起早起!這是大部分上班族的痛苦,但是不上班又是不可能的啦,因為都是為了搞錢

今天小編就用程式碼範例化,給大家展示一下不同的時鐘,希望大家按時上班,按時搞錢啦

一、Turtle繪製時鐘

1)程式碼展示

import turtle
from datetime import *
 
# 擡起畫筆,向前運動一段距離放下
def Skip(step):
    turtle.penup()
    turtle.forward(step)
    turtle.pendown()
 
def mkHand(name, length):
    # 註冊Turtle形狀,建立錶針Turtle
    turtle.reset()
    Skip(-length * 0.1)
    # 開始記錄多邊形的頂點。當前的烏龜位置是多邊形的第一個頂點。
    turtle.begin_poly()
    turtle.forward(length * 1.1)
    # 停止記錄多邊形的頂點。當前的烏龜位置是多邊形的最後一個頂點。將與第一個頂點相連。
    turtle.end_poly()
    # 返回最後記錄的多邊形。
    handForm = turtle.get_poly()
    turtle.register_shape(name, handForm)
 
def Init():
    global secHand, minHand, hurHand, printer
    # 重置Turtle指向北
    turtle.mode("logo")
    # 建立三個錶針Turtle並初始化
    mkHand("secHand", 135)
    mkHand("minHand", 125)
    mkHand("hurHand", 90)
    secHand = turtle.Turtle()
    secHand.shape("secHand")
    minHand = turtle.Turtle()
    minHand.shape("minHand")
    hurHand = turtle.Turtle()
    hurHand.shape("hurHand")
 
    for hand in secHand, minHand, hurHand:
        hand.shapesize(1, 1, 3)
        hand.speed(0)
 
    # 建立輸出文字Turtle
    printer = turtle.Turtle()
    # 隱藏畫筆的turtle形狀
    printer.hideturtle()
    printer.penup()
 
def SetupClock(radius):
    # 建立表的外框
    turtle.reset()
    turtle.pensize(7)
    for i in range(60):
        Skip(radius)
        if i % 5 == 0:
            turtle.forward(20)
            Skip(-radius - 20)
 
            Skip(radius + 20)
            if i == 0:
                turtle.write(int(12), align="center", font=("Courier", 14, "bold"))
            elif i == 30:
                Skip(25)
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))
                Skip(-25)
            elif (i == 25 or i == 35):
                Skip(20)
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))
                Skip(-20)
            else:
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))
            Skip(-radius - 20)
        else:
            turtle.dot(5)
            Skip(-radius)
        turtle.right(6)
 
def Week(t):  
    week = ["星期一", "星期二", "星期三",
            "星期四", "星期五", "星期六", "星期日"]
    return week[t.weekday()]
 
def Date(t):
    y = t.year
    m = t.month
    d = t.da
    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)
 
    turtle.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.hom()
    turtle.tracer(True)
 
    # 100ms後繼續呼叫tick
    turtle.ontimer(Tick, 100)
 
def main():
    # 開啟/關閉龜動畫,併為更新圖紙設定延遲。
    turtle.tracer(False)
    Init()
    SetupClock(160)
    turtle.tracer(True)
    Tick()
    turtle.mainloop()
 
if __name__ == "__main__":
    main()

2)效果展示

二、Turtle實現模擬時鐘

1)程式碼展示

基本思路:自定義shape,畫出時針、分針、秒針。通過register_shape()函數。 指標的位置通過shape類setheading()函數進行設定。 獲取系統時間作為當前時間,datetime.today()。 利用ontimer()函數定義定時器事件,觸發螢幕更新。 利用write()函數在螢幕上顯示文字。

from turtle import *
from datetime import datetime
 
mode("logo") # 向上(北),正角度為順時針
 
thisday = 0
thisecond = 0
 
second_hand = Turtle()
minute_hand = Turtle()
hour_hand = Turtle()
writer = Turtle()
writer.getscreen().bgcolor('gray90')
writer.color("gray20", "gray20")
 
def jump(distanz, winkel=0):
    penup()
    right(winkel)
    forward(distanz)
    left(winkel)
    pendown()
'''
laenge 指標長度
width 指標寬度
spitze 箭頭邊長
'''
def hand(laenge, spitze, width):
    lt(90)
    fd(width)
    rt(90)
    fd(laenge*1.15)
    rt(90)
    fd(width * 2)
    rt(90)
    fd(laenge*1.15)
    rt(90)
    fd(width)
    rt(90)
    fd(laenge*1.15)
    rt(90)
    fd(spitze/2.0)
    lt(120)
    fd(spitze)
    lt(120)
    fd(spitze)
    lt(120)
    fd(spitze/2.0)
 
def make_hand_shape(name, laenge, spitze, width):
    reset()
    jump(-laenge*0.15) # 指標靠近錶盤中心的末端,但不與圓心重合
    begin_poly()
    hand(laenge, spitze, width)
    end_poly()
    hand_form = get_poly()
    register_shape(name, hand_form)
 
 
def clockface(radius):
    reset()
    # 外圓周
    pensize(2)
    colors = ['green3', 'green2', 'gray98']
    # 從外向內fill
    for i in range(3):
        jump(radius+7+(2-i)*4,90)
        fillcolor(colors[i])
        begin_fill()
        circle(radius+7+(2-i)*4, steps=1000)
        end_fill()
        jump(-radius-7-(2-i)*4,90)
 
    # 刻度
    pensize(7)
    color("gray60", "gray60")
    # 經驗值
    params = [-35, -40, -40, -25, -15, -5, 0, -5, -15, -25, -40, -40] #距離
    angles = [0, -15, -25, -40, -35, -30, 0, 30, 35, 40, 25, 15] # 角度
    for i in range(60):
        jump(radius)
        if i % 5 == 0:
            fd(-15)
            # 下面三行寫錶盤數位
            jump(params[i/5], angles[i/5])
            write(12 if i/5==0 else i/5, align="center", font=("Courier", 20, "bold"))
            jump(params[i/5], 180+angles[i/5])
            jump(-radius+15)
        else:
            dot(3)
            jump(-radius)
        rt(6)
 
 
def setup():
    global second_hand, minute_hand, hour_hand, writer
    # 自定義形狀
    make_hand_shape("hour_hand", 90, 25, 5)
    make_hand_shape("minute_hand",  130, 25, 3)
    make_hand_shape("second_hand", 140, 10, 1)
 
    # 畫表盤
    clockface(160)
 
    hour_hand.shape("hour_hand")
    hour_hand.color("gray30", "gray12")
 
    minute_hand.shape("minute_hand")
    minute_hand.color("gray40", "blue")
 
    second_hand.shape("second_hand")
    second_hand.color("red4", "red4")
 
    for hand in hour_hand, minute_hand, second_hand:
        hand.resizemode("user")
        hand.shapesize(1, 1, 1)
        hand.speed(1)
    ht()
 
    writer.ht()
    writer.pu()
    writer.bk(85)
    
def wochentag():
    wochentag = ["星期一", "星期二", "星期三","星期四", "星期五", "星期六", "星期日"]
    return wochentag[t.weekday()]
 
def get_mmdd(z):
    m = z.month
    t = z.day
    return "%d月%d日" % (m, t)
 
def get_yyyy(z):
    j = z.year
    return "%d" % (j)
 
def write_date(t):
    global thisday
    x = t.day
    if thisday != x:
        thisday = x
        writer.clear()
        writer.home()
        writer.forward(65)
        writer.write(wochentag(t),
                 align="center", font=("Courier", 16, "bold"))
        writer.back(150)
        writer.write(get_mmdd(t),
                 align="center", font=("Courier", 16, "normal"))
        writer.back(15)
        writer.write(get_yyyy(t),
                 align="center", font=("Courier", 10, "normal"))
        writer.forward(100)
 
def tick():
    global thisecond
    t = datetime.today()
    if thisecond != t.second:
        thisecond = t.second
        #print t
        sekunde = t.second + t.microsecond * 0.000001
        minute = t.minute + sekunde / 60.0
        stunde = t.hour + minute / 60.0
        tracer(False)
        write_date(t)
        tracer(True)
        hour_hand.setheading(30 * stunde)
        minute_hand.setheading(6 * minute)
        second_hand.setheading(6 * sekunde)
    ontimer(tick, 10)
 
def main():
    tracer(False)
    setup()
    tracer(True)
    tick()
    return "EVENTLOOP"
 
if __name__ == "__main__":
    msg = main()
    print msg
    mainloop()

2)效果展示

三、簡易時鐘

1)程式碼展示

# coding=utf-8
import turtle
from datetime import *
 
 
# 由於錶盤刻度不連續,需頻繁擡起畫筆,放下畫筆
def skip(step):
    turtle.penup()  # 畫筆擡起
    turtle.forward(step)  # 畫筆移動step
    turtle.pendown()  # 畫筆落下
 
 
# 建立錶針,客製化錶針形狀和名字
def make_hand(name, length):
    turtle.reset()
 
    skip(-length * 0.1)  # 錶針一端,過錶盤中心一小段,開始繪製
    turtle.begin_poly()  # 開始記錄多邊形的第一個頂點。
    turtle.forward(length * 1.1)  # 設定錶針長度,繪製錶針
    turtle.end_poly()  # 停止記錄多邊形的頂點。當前的烏龜位置是多邊形的最後一個頂點。將與第一個頂點相連。
 
    handForm = turtle.get_poly()  # 返回最後記錄的形狀
 
    turtle.color('black')
    turtle.register_shape(name, handForm)
 
 
# 三個錶針初始化,範例化
def init_hand():
    global sec_hand, min_hand, hou_hand, printer
    # 重置Turtle指向北
    turtle.mode("logo")  # logo:向上(北) 順時針   standard:向右(東)  逆時針
 
    # 建立三個錶針Turtle並初始化
    make_hand("sec_Hand", 135)
    make_hand("min_Hand", 110)
    make_hand("hou_Hand", 70)
 
    sec_hand = turtle.Turtle()
    sec_hand.shape("sec_Hand")
    min_hand = turtle.Turtle()
    min_hand.shape("min_Hand")
    hou_hand = turtle.Turtle()
    hou_hand.shape("hou_Hand")
 
    # 筆的屬性
    for hand in sec_hand, min_hand, hou_hand:
        hand.shapesize(1, 1, 3)
        hand.speed(0)
 
    # 建立輸出列印的文字Turtle
    printer = turtle.Turtle()
 
    # 隱藏畫筆的turtle形狀
    printer.hideturtle()
    printer.penup()
 
 
# 設定錶盤
def set_clock(radius):
    turtle.reset()
    turtle.pencolor('red')  # 設定畫筆顏色
    turtle.fillcolor('pink')  # 設定繪製圖形的填充顏色
    turtle.pensize(10)  # 畫筆寬度
 
    for i in range(60):
        skip(radius)
        # 逢五 使用線條並加粗
        if i % 5 == 0:
            turtle.forward(20)
            skip(-radius - 20)
            skip(radius + 20)
 
            # 設定數位的位置及字型,大小
            if i == 0:
                turtle.write(int(12), align="center", font=("Courier", 14, "bold"))
            elif i == 30:
                skip(25)
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
                skip(-25)
            elif i == 25 or i == 35:
                skip(20)
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
                skip(-20)
            else:
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
            skip(-radius - 20)
        # 非五,以點代替
        else:
            turtle.dot(5)
            skip(-radius)
        turtle.right(6)
 
 
# 顯示星期
def show_week(t):
    week = ["星期一  Mon", "星期二  Tue", "星期三  Wed", "星期四  Thu", "星期五  Fri", "星期六  Sat", "星期日  Sun"]
    return week[t.weekday()]  # t.weekday() 週一為0,週二為1...可作為列表的index
 
 
# 顯示日期
def show_data(t):
    y = t.year
    m = t.month
    d = t.day
    return "{} 年 {} 月 {} 日".format(y, m, d)
 
 
# 顯示時間
# def show_time(t):
#     m = t.minute
#     h = t.hour
#     return "{}:{}".format(h, m)
 
 
# 顯示整個時鐘
def show_clock():
    # 獲取時間
    t = datetime.today()
    second = t.second + t.microsecond * 0.000001
    minute = t.minute + second / 60.0
    hour = t.hour + minute / 60.0
 
    sec_hand.setheading(6 * second)
    min_hand.setheading(6 * minute)
    hou_hand.setheading(30 * hour)
 
    turtle.tracer(False)
 
    printer.forward(65)
    printer.write(show_week(t), align='center', font=("Courier", 14, "bold"))
 
    printer.back(65)
    printer.write("The Clock of Hua", align="center", font=("Courier", 16, "bold"))
 
    printer.back(65)
    printer.write(show_data(t), align='center', font=("Courier", 14, "bold"))
 
    # printer.back(25)
    # printer.write(show_time(t), align="center", font=("Courier", 14, "bold"))
    # 回到原點,以便於下一輪的顯示
    printer.home()
    turtle.tracer(True)
 
    # 100ms後繼續呼叫show_clock
    turtle.ontimer(show_clock, 100)
 
 
# main函數
def main():
    turtle.tracer(False)
    # 設定背景
    ts = turtle.getscreen()
    ts.bgcolor("#cccccc")
    # 初始化
    init_hand()
    # 設定時鐘
    set_clock(180)
    turtle.tracer(True)
    # 顯示時鐘
    show_clock()
    turtle.mainloop()
 
 
if __name__ == "__main__":
    main()

2)效果展示

以上就是基於Python製作三款起床鬧鐘的範例程式碼的詳細內容,更多關於Python起床鬧鐘的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com