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

如何在Python程序内实现实时更新且不弹出新窗口的时钟

实现方案

完全可以实现无新窗口的行内实时时钟,不需要弹出独立GUI窗口,核心是在当前程序运行的终端/已有界面的固定位置反复刷新时间内容,避免创建新的窗口对象。

基础终端版(单文件直接运行)

这个版本运行后会在你执行脚本的当前终端行固定显示HH:MM格式的时间,不会滚屏、不会弹新窗,按Ctrl+C即可退出:

import time
from datetime import datetime

try:
    while True:
        # 格式化时间为和示例一致的 时:分 格式,需要带秒可改成"%H:%M:%S"
        now = datetime.now().strftime("%H:%M")
        # \r 让光标回到当前行首,end="" 阻止print默认追加换行,flush=True强制实时输出
        print(f"\r{now}", end="", flush=True)
        # 每秒刷新一次,若只需要精确到分钟可把间隔改成60
        time.sleep(1)
except KeyboardInterrupt:
    # 退出时换行,避免命令行提示符和时钟内容挤在同一行
    print()

嵌入现有程序版(不阻塞主逻辑)

如果需要把时钟嵌到你正在运行的命令行程序里,不阻塞原有业务逻辑,可以用守护线程跑时钟更新:

import time
import threading
from datetime import datetime

class InlineClock:
    def __init__(self, time_format="%H:%M"):
        self.running = False
        self.time_format = time_format
        self._thread = None

    def _refresh_loop(self):
        while self.running:
            current_time = datetime.now().strftime(self.time_format)
            print(f"\r{current_time}", end="", flush=True)
            time.sleep(1)

    def start(self):
        """启动行内时钟"""
        self.running = True
        self._thread = threading.Thread(target=self._refresh_loop, daemon=True)
        self._thread.start()

    def stop(self):
        """停止时钟"""
        self.running = False
        print()

# 调用示例
if __name__ == "__main__":
    clock = InlineClock()
    clock.start()
    # 下方写你自己的程序主逻辑即可,时钟会在当前行固定位置实时更新
    try:
        # 模拟主程序运行
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        clock.stop()

注意事项

  • 如果需要在时钟运行时输出其他内容,先输出换行符再打印内容,否则新内容会和时钟显示挤在同一行,下一次时钟刷新会自动覆盖行首内容。
  • 如果你使用的是TUI框架(比如curses、textual)或者已有GUI窗口(比如你程序已经开了一个tkinter/PyQt窗口),只需要把上述代码里的print替换成对应框架的文本组件更新逻辑,绑定框架自带的定时器即可,不需要新建顶层窗口。
  • 网上搜到的弹窗时钟示例本质是默认新建了独立GUI顶层窗口,只要跳过新建窗口的步骤,把时间渲染到已有界面元素上就符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 02:01:23