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

Python Tkinter本地时钟不运行问题求助

问题解决:Tkinter本地时间时钟无法运行的修复

错误核心原因

你的代码存在两个致命问题:

  1. 变量调用顺序颠倒:在localtime()和time_utc()函数中,你先尝试用mark.config()更新文本,但此时mark标签还没创建,第一次执行就会触发NameError,直接导致本地时间时钟崩溃。
  2. 重复创建组件:每次调用时钟函数都会重新生成一个Label并执行pack,会不断在窗口添加新标签,造成界面混乱。

修复后的完整代码

from tkinter import *
import datetime

root = Tk()
root.geometry("500x500")
root.resizable(0,0)
root.title('Python Clock')

# 提前创建本地时间标签
local_mark = Label(root, 
    font = ('calibri', 40, 'bold'),
    pady=50,
    foreground = 'blue')
local_mark.pack(anchor='center')

def localtime():
    now = datetime.datetime.now()
    string = now.strftime('%H:%M:%S')
    local_mark.config(text=string)
    local_mark.after(1000, localtime)

# 提前创建UTC时间标签
utc_mark = Label(root, 
    font = ('calibri', 40, 'bold'),
    pady=50,
    foreground = 'blue')
utc_mark.pack(anchor='s')

def time_utc():
    now = datetime.datetime.utcnow()
    string = now.strftime('%H:%M:%S')
    utc_mark.config(text=string)
    utc_mark.after(1000, time_utc)

# 启动两个时钟
localtime()
time_utc()

mainloop()

关键修改说明

  • 把Label组件的创建移到函数外部,确保更新文本时组件已存在
  • 给两个标签分别命名(local_mark和utc_mark),避免变量名冲突
  • 调整pady值,让两个时钟在窗口中分布更合理
  • 函数内只负责更新文本和设置下一次定时调用,不再重复创建组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 20:43:24