首先展示代码:
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 26 11:00:23 2023
@author: admin
"""
import tkinter # 导入Python GUI库
import math # 导入数学库,用于计算坐标
import time # 导入时间库,用于获取当前时间
# 定义一个继承自Tkinter.Tk的main类,用于创建窗口并添加组件
class main(tkinter.Tk):
def __init__(self):
tkinter.Tk.__init__(self)
self.x = 150 # 中心点x坐标
self.y = 150 # 中心点y坐标
self.length = 40 # 指针长度
self.creating_all_function_trigger() # 调用初始化方法
# 触发器
def creating_all_function_trigger(self):
self.create_canvas_for_shapes() # 创建画布
self.creating_background_() # 创建背景
self.creating_sticks() # 创建指针
return
# 创建背景
def creating_background_(self):
self.image = tkinter.PhotoImage(file='cl.png') # 从文件中导入图片
self.canvas.create_image(151, 124, image=self.image) # 在画布上添加图片
return
# 创建画布
def create_canvas_for_shapes(self):
self.canvas = tkinter.Canvas(self, bg='black') # 创建画布对象,并将其添加到主视窗中
self.canvas.pack(expand='yes', fill='both') # 将画布填充整个窗口
return
# 创建指针
def creating_sticks(self):
self.sticks = [] # 初始化指针列表
for i in range(3): # 循环3次,创建时钟上的三个指针
store = self.canvas.create_line(self.x, self.y, self.x+self.length, self.y+self.length, width=2, fill='red') # 在画布上创建直线指针
self.sticks.append(store) # 将指针添加到指针列表中
return
def update_class(self):
now = time.localtime() # 获取当前时间
t = time.strptime(str(now.tm_hour), "%H") # 格式化小时数,并转换成time格式(因为小时数可能大于12)
hour = int(time.strftime("%I", t))*5 # 获得12小时时间制的小时数,将其乘以5得到60分钟制的小时数
now = (hour, now.tm_min, now.tm_sec) # 将当前时间转换为一个元组,便于处理
for n, i in enumerate(now):
x, y = self.canvas.coords(self.sticks[n])[0:2] # 获得第n个指针的起始坐标
cr = [x, y] # 创建坐标列表
cr.append(self.length*math.cos(math.radians(i*6)-math.radians(90))+self.x) # 计算指针的结束x坐标
cr.append(self.length*math.sin(math.radians(i*6)-math.radians(90))+self.y) # 计算指针的结束y坐标
self.canvas.coords(self.sticks[n], tuple(cr)) # 将指针移动至新的位置
return
if __name__ == '__main__':
root = main() # 创建main类对象
while True: # 循环更新指针位置
root.update()
root.update_idletasks()
root.update_class() # 调用update_class方法,将指针移动至新的位置
结果展示:
注意:这个钟是会动的。
关键步骤:在桌面建立一个文件夹保存代码,并且导入一个属性为png的时钟图片。(一开始因为这个图片的选择了jpn所以老是不对,弄不出来。时钟图片尽量不要选带指针的,会更好看)