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

Python Tkinter倒计时标签显示异常,请求排查解决

问题分析与修复方案

你的代码存在三个关键问题,导致显示结果不符合预期:

  • now变量仅在程序启动时获取一次当前时间,后续不会自动更新,时间差会固定不变。
  • label.config(text=str(time_remaining))错误地将函数对象转为字符串显示,应该使用计算得到的时间差变量daysdiff。
  • 缺少定时刷新逻辑,无法实时更新剩余时间。

修正后的代码如下:

import tkinter as tk
import datetime

date1 = datetime.datetime(2023, 11, 1)

def timer_label(label):
    def time_remaining():
        now = datetime.datetime.now()  # 每次刷新都重新获取当前时间
        daysdiff = str(date1 - now)
        label.config(text=daysdiff)  # 显示计算出的时间差
        # 每隔1秒自动刷新一次
        root.after(1000, time_remaining)
    time_remaining()

root = tk.Tk()
root.title('Days to Closure')

label = tk.Label(root, fg="red", font=("Arial", 16))
label.pack(pady=20)
timer_label(label)
button = tk.Button(root, text='CLOSE', width=25, command=root.destroy)
button.pack(pady=10)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:55:53