python好看的钟表
时间: 2025-01-03 16:35:58 浏览: 6
### Python 实现美观的数字时钟
为了创建一个美观的数字时钟,可以使用 `tkinter` 库来构建图形用户界面 (GUI),并利用其内置的小部件显示时间。
```python
import tkinter as tk
from time import strftime
def update_time():
current_time = strftime('%H:%M:%S %p')
label.config(text=current_time)
root.after(1000, update_time)
root = tk.Tk()
root.title("Digital Clock")
label = tk.Label(root, font=('calibri', 40, 'bold'), background='purple', foreground='white')
label.pack(anchor='center')
update_time()
root.mainloop()
```
这段代码定义了一个简单的窗口应用程序,其中包含一个标签用于展示当前的时间。每秒钟会调用一次 `update_time()` 函数刷新时间显示[^1]。
### 使用Tkinter实现模拟时钟
对于更复杂的模拟时钟,则可以通过自定义画布上的绘图操作完成指针位置计算与渲染:
```python
import tkinter as tk
from math import pi, sin, cos
from datetime import datetime
class AnalogClock(tk.Canvas):
def __init__(self, master=None, **kwargs):
super().__init__(master=master, bg='black', highlightthickness=0, **kwargs)
self.width = int(self['width'])
self.height = int(self['height'])
center_x = self.width / 2
center_y = self.height / 2
radius = min(center_x, center_y) * 0.9
# Draw clock face and numbers
for i in range(60):
angle = i * (pi/30) - pi/2
inner_radius = radius if i%5==0 else radius*0.9
outer_radius = radius if i%5!=0 else radius*0.8
x1 = center_x + cos(angle)*inner_radius
y1 = center_y + sin(angle)*inner_radius
x2 = center_x + cos(angle)*outer_radius
y2 = center_y + sin(angle)*outer_radius
self.create_line(x1,y1,x2,y2,width=(i%5==0)*2+1,fill='#ffffff')
if i%5==0:
text_angle = str((i//5)%12 or 12)
tx = center_x + cos(angle)*(radius*.7)
ty = center_y + sin(angle)*(radius*.7)
self.create_text(tx,ty,text=text_angle,
fill="#ffffff",font=("Helvetica",int(radius//10)))
def draw_hands(self):
now = datetime.now().time()
hour = now.hour % 12
minute = now.minute
second = now.second
angles = [
((hour * 60 + minute)/720 - .25),
(minute/60 - .5),
(second/60 - .5)]
lengths = [.5,.65,.8]
colors = ["#ffcc00","#ffffff","#ff0000"]
center_x = self.width / 2
center_y = self.height / 2
radius = min(center_x, center_y) *.9
for idx,(angle,length,color) in enumerate(zip(angles,lengths,colors)):
end_x = center_x + cos(pi*(angle))*length*radius
end_y = center_y + sin(pi*(angle))*length*radius
hand_id = f'hand{idx}'
try:
coords = self.coords(hand_id)
self.coords(hand_id,*coords[:2],end_x,end_y)
except Exception:
self.create_line(
center_x,center_y,end_x,end_y,tags=[hand_id],
arrow=tk.LAST,arrowshape=(10,12,5),width=max(int(length*2),1),
fill=color)
if __name__ == '__main__':
app = tk.Tk()
app.title('Analog Clock')
canvas_width = 400
canvas_height = 400
analog_clock = AnalogClock(app, width=canvas_width, height=canvas_height)
analog_clock.pack(expand=True, fill='both')
def tick():
analog_clock.draw_hands()
app.after(1000 // 60, tick)
tick()
app.mainloop()
```
此脚本实现了完整的模拟时钟功能,包括绘制表盘刻度线、数字标记以及不断移动的手臂。手臂的角度基于实际时间和π的关系进行调整,从而使得整个动画看起来非常流畅自然[^2].
阅读全文