You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter模拟时钟运行1秒后停止的问题求助

解决Tkinter模拟时钟指针停止的问题

问题根源

你的时钟指针仅移动一次就停止,核心原因是**after()方法仅被调用了一次**,未形成循环触发逻辑;另外小时指针的计算缺少分钟偏移,会导致小时指针跳变而非平滑移动。

修复步骤

  1. 循环触发更新函数
    在live_clock()函数末尾添加canvas.after(1000, live_clock),每次执行完更新逻辑后,自动预约1秒后再次执行该函数,实现持续更新。

  2. 修正小时指针角度计算
    原代码仅按整小时计算小时指针角度,实际应加入分钟偏移量(每分钟小时指针转动0.5度),修改后的角度公式为:math.radians(hour * 30 + mint * 0.5)。

修正后的完整代码

# imports
import tkinter as cl
import time
import math

# creating window
window = cl.Tk()
window.title("analog clock :3")
window.geometry("400x400")

# customising canvas
canvas = cl.Canvas(width=400, height=400, bg="black")
canvas.pack()

# importing images
bg = cl.PhotoImage(file=r"D:\PythonProjects\dial.png")  # 加r前缀避免路径转义问题
canvas.create_image(200, 200, image=bg)

# making the hands of the clock
sec_hand_len = 90
min_hand_len = 80
hour_hand_len = 60
center_x = 200
center_y = 200

sec_hand = canvas.create_line(200, 200, 200 + sec_hand_len, 200 + sec_hand_len, width=1.5, fill="red")
min_hand = canvas.create_line(200, 200, 200 + min_hand_len, 200 + min_hand_len, width=2, fill="black")
hour_hand = canvas.create_line(200, 200, 200 + hour_hand_len, 200 + hour_hand_len, width=4, fill="black")


# defining func. and adding time
def live_clock():
    hour = int(time.strftime("%I"))
    mint = int(time.strftime("%M"))
    sec = int(time.strftime("%S"))

    # 计算秒针坐标
    sec_x = sec_hand_len * math.sin(math.radians(sec * 6)) + center_x
    sec_y = -1 * sec_hand_len * math.cos(math.radians(sec * 6)) + center_y
    canvas.coords(sec_hand, center_x, center_y, sec_x, sec_y)

    # 计算分针坐标
    min_x = min_hand_len * math.sin(math.radians(mint * 6)) + center_x
    min_y = -1 * min_hand_len * math.cos(math.radians(mint * 6)) + center_y
    canvas.coords(min_hand, center_x, center_y, min_x, min_y)

    # 计算时针坐标(加入分钟偏移)
    hour_angle = hour * 30 + mint * 0.5  # 每小时30度,每分钟额外0.5度
    hour_x = hour_hand_len * math.sin(math.radians(hour_angle)) + center_x
    hour_y = -1 * hour_hand_len * math.cos(math.radians(hour_angle)) + center_y
    canvas.coords(hour_hand, center_x, center_y, hour_x, hour_y)

    # 预约下一次更新
    canvas.after(1000, live_clock)


# 启动时钟更新
live_clock()
window.mainloop()

额外提示

  • 图片路径添加r前缀(原始字符串),可避免路径中的反斜杠被当作转义字符处理。
  • 原代码中注释的公式存在笔误(sign应为sin),修正代码中已移除无关注释。

内容的提问来源于stack exchange,提问作者StormFire1122

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 17:45:28