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

如何用Tkinter实现启停秒表的单按钮GUI并显示计算结果

Tkinter单按钮启停秒表并显示计算结果解决方案

你的代码存在几个核心问题:用time.sleep()和while循环阻塞了Tkinter主事件循环,导致GUI无响应;KeyboardInterrupt在GUI环境下无法触发;没有设计按钮状态切换逻辑,也没有添加显示结果的组件。下面是修复后的完整代码:

import time
from tkinter import *

window = Tk()
window.title("秒表计算工具")

# 用于显示计算结果的标签,放在按钮上方
result_label = Label(window, text="Height: 0 meters", font=("Ink Free", 20))
result_label.pack(pady=20)

button = Button(window, text="Start", font=("Ink Free", 50, "bold"), 
                bg="#32a2a8", fg="#99a832", 
                activebackground="#FF0000", activeforeground="#99a832")

# 状态变量:标记秒表是否正在运行
is_running = False
start_time = 0
after_id = None

def update_timer():
    """更新计时,每秒刷新一次"""
    global after_id
    elapsed_time = time.time() - start_time
    after_id = window.after(1000, update_timer)

def toggle_timer():
    """切换秒表的启动/停止状态"""
    global is_running, start_time, after_id
    if not is_running:
        # 启动秒表
        is_running = True
        button.config(text="Stop")
        start_time = time.time()
        update_timer()
    else:
        # 停止秒表
        is_running = False
        button.config(text="Start")
        window.after_cancel(after_id)
        # 计算时长和高度
        elapsed_time = round(time.time() - start_time, 2)
        height = round(4.905 * elapsed_time ** 2)
        result_label.config(text=f"Height: {height} meters")

button.config(command=toggle_timer)
button.pack(pady=20)

window.mainloop()

关键修改说明

  • 状态控制:新增is_running变量,点击按钮时切换状态,实现同一个按钮的启停切换
  • 非阻塞计时:使用Tkinter的after()方法实现定时刷新,完全避免了time.sleep()导致的GUI卡顿问题
  • 结果显示:添加result_label组件,专门用来展示计算后的高度值,替代原代码中的控制台打印
  • 逻辑重构:拆分计时和状态切换逻辑,启动时记录开始时间并循环更新计时,停止时计算结果并更新UI

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:46:17