如何使用tkinter構(gòu)建數(shù)字時鐘
用tkinter創(chuàng)建一個數(shù)字時鐘,最終效果圖如下
點擊界面時,切換到日期,還可以再切換回來
看起來挺有趣的,開始code吧
首先創(chuàng)建出窗口
from tkinter import *from time import strftimeroot = Tk()root.title("python時鐘")
在窗口上安放一個Lable控件,控件的背景色是黑色,字體為白色,填充整個窗口
# 界面有多大,完全是靠字體撐起來的, 背景是黑色, 字體是白色lbl = Label(root, font=("arial", 100, "bold"), \bg="black", fg="white")lbl.pack(anchor="center", fill="both", expand=1)
接下來,需要考慮如何讓時間動起來,Label有一個after方法,可以指定在一定時間后,執(zhí)行某個函數(shù),可以在這個函數(shù)里修改Label上顯示的內(nèi)容。
還要考慮點擊Label之后,從顯示小時轉(zhuǎn)變?yōu)轱@示日期,因此需要給Label綁定一個click事件
mode = 'hour'def showtime():if mode == 'hour':string = strftime("%H:%M:%S %p")else:string = strftime("%Y-%m-%d")lbl.config(text=string)lbl.after(1000, showtime)def mouse_click(event):global modeif mode == 'hour':mode = 'day'else:mode = 'hour'lbl.bind("<Button>", mouse_click)showtime()mainloop()
在mouse_click函數(shù)里,改變mode的值,showtime函數(shù)根據(jù)mode的值來決定
顯示什么內(nèi)容,大功告成啦。
評論
圖片
表情
