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

Python开发tkinter定时器时如何将datetime时间差显示调整为整秒格式

代码修改方案

1. 实现秒级时间显示

原代码直接输出datetime.timedelta对象会默认附带微秒,需截断微秒精度后渲染:

  • 计算时长时,通过dur - datetime.timedelta(microseconds=dur.microseconds)清除微秒部分,输出格式自动变为H:MM:SS

2. 修正Start按钮启动逻辑

原代码存在两个缺陷:

  • 计时起点start在窗口初始化时就赋值,未点击Start就已开始计时
  • 无运行状态锁,多次点击Start会触发多个after循环导致计时混乱
    需新增is_running状态标记,仅首次点击Start时记录计时起点

3. 修复原代码语法/逻辑bug

  • 删除重复的import time, datetime冗余导入(time模块未实际使用)
  • 修正窗口置顶参数拼写错误:-topmos → -topmost
  • 补充frame的布局代码(原代码创建frame后未挂载到主窗口)
  • 修正主循环调用对象:frame.mainloop() → win.mainloop()(Frame无mainloop方法,需调用主窗口的mainloop)

完整可运行代码

import datetime
import tkinter as tk

# 主窗口初始化
win = tk.Tk()
win.geometry('200x100+550+250')
win.title('Timer')
win.config(bg='#323232')
win.attributes('-topmost', 1)

# 计时状态标记
is_running = False
start = None

frame = tk.Frame()
frame.pack()

lab = tk.Label(frame, text='0:00:00', bg='#000000', fg='#FFFFFF')
lab.pack()

def update():
    global is_running, start
    # 计算时长并截断微秒
    dur = datetime.datetime.now() - start
    dur = dur - datetime.timedelta(microseconds=dur.microseconds)
    lab.config(text=dur)
    frame.after(20, update)

def start_timer():
    global is_running, start
    # 仅未运行时才启动计时
    if not is_running:
        is_running = True
        start = datetime.datetime.now()
        update()

# Start按钮绑定启动函数
St_button = tk.Button(frame, text='Start', command=start_timer)
St_button.pack()

win.mainloop()

可选:强制补零格式化

如果需要固定显示两位小时(如00:00:00而非0:00:00),可替换update函数内的渲染逻辑:

def update():
    global is_running, start
    dur = datetime.datetime.now() - start
    # 取整总秒数后拆分格式化
    total_sec = int(dur.total_seconds())
    h = total_sec // 3600
    m = (total_sec % 3600) // 60
    s = total_sec % 60
    lab.config(text=f"{h:02d}:{m:02d}:{s:02d}")
    frame.after(20, update)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 21:06:03