Python+Tkinter繪制一個數(shù)字時鐘
Tkinter 實現(xiàn)上述功能并不復(fù)雜,只要使用 Tkinter 的相關(guān)組件和一些簡單的邏輯處理即可,在編寫這個案例的過程中大家要做到溫故而知新。
程序代碼如下所示:
from tkinter import * from time import strftime root = Tk() root.geometry('500x350+300+300') root.iconbitmap('C:/Users/Administrator/Desktop/C語言中文網(wǎng)logo.ico') root.title("C語言中文網(wǎng)出品") # 設(shè)置文本標(biāo)簽 lb = Label(root, font=("微軟雅黑", 50, "bold"), bg='#87CEEB', fg="#B452CD") lb.pack(anchor="center", fill="both", expand=1) # 定義一個mode標(biāo)志 mode = 'time' # 定義顯示時間的函數(shù) def showtime(): if mode == 'time': #時間格式化處理 string = strftime("%H:%M:%S %p") else: string = strftime("%Y-%m-%d") lb.config(text=string) # 每隔 1秒鐘執(zhí)行time函數(shù) lb.after(1000, showtime) # 定義鼠標(biāo)處理事件,點擊時間切換為日期樣式顯示 def mouseClick(event): global mode if mode == 'time': # 點擊切換mode樣式為日期樣式 mode = 'date' else: mode = 'time' lb.bind("<Button>", mouseClick) # 調(diào)用showtime()函數(shù) showtime() # 顯示窗口 mainloop()
程序運行結(jié)果如下:
圖1:簡單的數(shù)字時鐘
通過上述代碼就實現(xiàn)了一個簡單的數(shù)字時鐘,是不是非常的簡單。
補充
除了數(shù)字時鐘,Tkinter還能繪制一個簡易的鐘表
具體實現(xiàn)代碼如下:
# 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()
效果如下
到此這篇關(guān)于Python+Tkinter繪制一個數(shù)字時鐘的文章就介紹到這了,更多相關(guān)Python Tkinter數(shù)字時鐘內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python連接mongodb數(shù)據(jù)庫操作數(shù)據(jù)示例
這篇文章主要介紹了python連接mongodb操作數(shù)據(jù)示例,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-11-11關(guān)于Python中flask-httpauth庫用法詳解
這篇文章主要介紹了關(guān)于Python中flask-httpauth庫用法詳解,Flask-HTTPAuth是一個?Flask?擴展,它簡化了?HTTP?身份驗證與?Flask?路由的使用,需要的朋友可以參考下2023-04-04