日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python+Tkinter繪制一個數字時鐘_python

作者:嚴長生 ? 更新時間: 2022-04-02 編程語言

Tkinter 實現上述功能并不復雜,只要使用 Tkinter 的相關組件和一些簡單的邏輯處理即可,在編寫這個案例的過程中大家要做到溫故而知新。

程序代碼如下所示:

from tkinter import *
from time import strftime
root = Tk()
root.geometry('500x350+300+300')
root.iconbitmap('C:/Users/Administrator/Desktop/C語言中文網logo.ico')
root.title("C語言中文網出品")
# 設置文本標簽
lb = Label(root, font=("微軟雅黑", 50, "bold"), bg='#87CEEB', fg="#B452CD")
lb.pack(anchor="center", fill="both", expand=1)
# 定義一個mode標志
mode = 'time'
# 定義顯示時間的函數
def showtime():
    if mode == 'time':
        #時間格式化處理   
        string = strftime("%H:%M:%S %p")
    else:
        string = strftime("%Y-%m-%d")
    lb.config(text=string)
    # 每隔 1秒鐘執行time函數
    lb.after(1000, showtime)
# 定義鼠標處理事件,點擊時間切換為日期樣式顯示
def mouseClick(event):
    global mode
    if mode == 'time':
        # 點擊切換mode樣式為日期樣式
        mode = 'date'
    else:
        mode = 'time'
lb.bind("<Button>", mouseClick)
# 調用showtime()函數
showtime()
# 顯示窗口
mainloop()

程序運行結果如下:

圖1:簡單的數字時鐘

通過上述代碼就實現了一個簡單的數字時鐘,是不是非常的簡單。

補充

除了數字時鐘,Tkinter還能繪制一個簡易的鐘表

具體實現代碼如下:

# coding:utf-8
from tkinter import *
import math,time
def points():
 for i in range(1,13):
 x = 200 + 130*math.sin(2*math.pi*i/12)
 y = 200 - 130*math.cos(2*math.pi*i/12)
 canvas.create_text(x,y,text=i)

def createline(radius,line_width,rad):
 global List
 global i
 List = []
 x = 200+radius*math.sin(rad)
 y = 200-radius*math.cos(rad)
 i=canvas.create_line(200,200,x,y,width=line_width)
 List.append(i)

root = Tk()
root.resizable(0,0)
canvas = Canvas(root,width=400,height=500,bd=0,highlightthickness=0)
canvas.pack()
canvas.create_oval(50,50,350,350)
points()

while 1:
 tm=time.localtime()
 t=time.asctime(tm)
 t_hour=0
 if tm.tm_hour<=12:
 t_hour=tm_hour
 else:
 t_hour=tm.tm_hour-12
 rad1=2*math.pi*(t_hour+tm.tm_min/60)/12
 rad2=2*math.pi*(tm.tm_min+tm.tm_sec/60)/60
 rad3=2*math.pi*tm.tm_sec/60
 createline(50,6,rad1,)
 createline(90,3,rad2)
 createline(120,1,rad3)
 l=canvas.create_text(170,450,text=t)
 root.update()
 time.sleep(1)
 for item in List:
 canvas.delete(item)
 canvas.delete(l)

root.update()
mainloop()

效果如下

原文鏈接:http://c.biancheng.net/tkinter/project-case.html

欄目分類
最近更新