import tkinter as tk
import time
from tkinter import messagebox

# 创建主窗口
root = tk.Tk()
root.geometry("300x400")  # 设置窗口大小
root.title("10秒挑战")

bg_image = tk.PhotoImage(file ='十秒挑战.png')
bg_label = tk.Label(root, image = bg_image)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)

# 初始化运行状态
flag = False

# 定期更新显示时间
def update_time():
    if flag:
        now = time.time()
        timex = now - start_time
        timex_label.config(text=f"时间：{timex:.3f} 秒\n")
        root.after(10, update_time)  # 10ms 后更新一次

# 根据当前状态开始或停止计时
def change():
    global flag, start_time

    if not flag:  # 如果计时尚未开始
        flag = True
        start_time = time.time()  # 获取当前时间戳
        update_time()  # 开始更新时间显示
    else:  # 如果计时已经开始
        flag = False  # 停止更新时间显示
        end_time = time.time()  # 获取当前时间戳
        timex = end_time - start_time  # 计算实际耗时
        goal = 10  # 目标耗时

        # 计算时间差
        time_difference = abs(timex - goal)

        # 更新显示
        timex_label.config(text=f"实际时间：{timex:.3f}秒\n误差：{time_difference:.3f}秒")

        # 显示结果
        if f'{time_difference:.3f}' == '0.000':
            messagebox.showinfo("结果","难以置信！你就是掌控时间的神！")
        else:
            messagebox.showinfo("结果","还差一点点，再接再厉吧！")

# 创建标签
title_label = tk.Label(root, text="10 秒挑战", font=("楷体", 16))
title_label.pack(pady=(72,10))

# 创建时间显示标签
timex_label = tk.Label(root, text="点击按钮开始挑战\n", font=("楷体", 12))
timex_label.pack(pady=(22,17))

# 创建按钮并设置图片
btn_photo = tk.PhotoImage(file ='按钮.png')
btn = tk.Button(root, image=btn_photo, command=change)
btn.pack(pady=20)

# 运行Tkinter主循环
root.mainloop()