持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情
准备工作
我用的是pycharm,其他的不用准备了。用到的组件库tkinter,是python系统自带的。
代码内容
from tkinter import*
import math,time
class MyGuiClock:
def __init__(self):
self.root=Tk()
self.root.title("图形时钟")
self.root.resizable(0,0)
self.canvas=Canvas(self.root,width=400,height=500)
self.canvas.pack()
self.root.protocol("WM_DELETE_WINDOM",self.handler)
self.run=True
def createPoints(self):
self.canvas.create_oval(50,50,350,350)
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)
self.canvas.create_text(x,y,text=i)
def createLine(self,radius,line_width,rad):
x=200+radius*math.sin(rad)
y=200-radius*math.cos(rad)
self.canvas.create_line(200,200,x,y,width=line_width)
def handler(self):
self.run=False
def showGui(self):
while self.run:
tm=time.localtime()
t=time.asctime(tm)
if tm.tm_hour<=12:
t_hour=tm.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
self.createPoints()
self.createLine(50,6,rad1)
self.createLine(90,3,rad2)
self.createLine(120,1,rad3)
self.canvas.create_text(170,450,text=t)
self.root.update()
self.canvas.delete('all')
self.root.destroy()
if __name__=='__main__':
myClock=MyGuiClock()
myClock.showGui()
效果演示
浅分析一下
调用函数
from tkinter import*
import math,time
调用tkinter组件库的全部组件(* 全部调用 ),调用函数math,后面会用到数学函数(sec)。
先制作一个面板
def __init__(self):
self.root=Tk()
self.root.title("图形时钟")
self.root.resizable(0,0)
self.canvas=Canvas(self.root,width=400,height=500)
self.canvas.pack()
self.root.protocol("WM_DELETE_WINDOM",self.handler)
self.run=True
制作一个面板,给它命名为“图形时钟”,并设置面板不可缩放的状态,设置面板的大小,当点击叉号时触发self.handle 关闭窗口。
制作表盘
def createPoints(self):
self.canvas.create_oval(50,50,350,350)
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)
self.canvas.create_text(x,y,text=i)
def createLine(self,radius,line_width,rad):
x=200+radius*math.sin(rad)
y=200-radius*math.cos(rad)
self.canvas.create_line(200,200,x,y,width=line_width)
在左上顶点(50,50)处设置一个点,在右下角点(350,350)处设置一个点,两点连接成一个矩形(正方形)的区域内画一个椭圆(圆形)。在1到12个数进行角度变换。通过数学函数进行点的计算,下一个点和上一点与圆心直接的联系成30度。这样,表盘就做好了。
制作时针
def showGui(self):
while self.run:
tm=time.localtime() #导入时间戳
t=time.asctime(tm) #导入时间信息,年月日周期时间
if tm.tm_hour<=12:
t_hour=tm.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 #秒针
self.createPoints()
self.createLine(50,6,rad1)
self.createLine(90,3,rad2)
self.createLine(120,1,rad3)
self.canvas.create_text(170,450,text=t)
self.root.update()
self.canvas.delete('all')
self.root.destroy()
导入时间戳等信息,当小时数小于12时,执行时针分针秒针;当小时数大于12时,对该数进行减12(24小时制)。对时针分针秒针进行粗细和长度的区别,对导入的年月日周期时间进行文本显示,对上方内容进行刷新,对上方内容进行删除,重复执行。当不运行时,对函数进行破坏。
判定是否执行
def handler(self):
self.run=False
上方执行该函数时,停止运行。
将类转换
if __name__=='__main__':
myClock=MyGuiClock()
myClock.showGui()
类class是不能执行的,需要把它转换。