import tkinter as tk
from tkinter import messagebox

def convert():
    """执行温度转换并显示结果"""
    try:
        # 获取输入温度值
        temp = float(entry_temp.get())
        in_unit = from_unit.get()
        out_unit = to_unit.get()

        # 如果单位相同，直接输出原值
        if in_unit == out_unit:
            result = temp
        else:
            # 统一转换为摄氏度作为中间值
            if in_unit == "摄氏度":
                celsius = temp
            elif in_unit == "华氏度":
                celsius = (temp - 32) * 5 / 9
            elif in_unit == "开尔文":
                celsius = temp - 273.15
            else:
                raise ValueError("未知输入单位")

            # 从摄氏度转换为目标单位
            if out_unit == "摄氏度":
                result = celsius
            elif out_unit == "华氏度":
                result = celsius * 9 / 5 + 32
            elif out_unit == "开尔文":
                result = celsius + 273.15
            else:
                raise ValueError("未知输出单位")

        # 显示结果（保留两位小数）
        label_result.config(text=f"结果: {result:.2f} {out_unit}")

    except ValueError:
        messagebox.showerror("输入错误", "请输入有效的数字温度值！")

# 创建主窗口
root = tk.Tk()
root.title("温度单位转换器")
root.geometry("320x220")  # 设置窗口大小
root.resizable(False, False)  # 禁止调整窗口大小

# 第一行：温度输入
tk.Label(root, text="输入温度:", font=("Arial", 10)).grid(row=0, column=0, padx=10, pady=8, sticky="e")
entry_temp = tk.Entry(root, width=15, font=("Arial", 10))
entry_temp.grid(row=0, column=1, padx=10, pady=8, sticky="w")

# 第二行：输入单位
tk.Label(root, text="输入单位:", font=("Arial", 10)).grid(row=1, column=0, padx=10, pady=8, sticky="e")
from_unit = tk.StringVar(value="摄氏度")
units = ["摄氏度", "华氏度", "开尔文"]
option_from = tk.OptionMenu(root, from_unit, *units)
option_from.config(width=10, font=("Arial", 10))
option_from.grid(row=1, column=1, padx=10, pady=8, sticky="w")

# 第三行：输出单位
tk.Label(root, text="输出单位:", font=("Arial", 10)).grid(row=2, column=0, padx=10, pady=8, sticky="e")
to_unit = tk.StringVar(value="华氏度")
option_to = tk.OptionMenu(root, to_unit, *units)
option_to.config(width=10, font=("Arial", 10))
option_to.grid(row=2, column=1, padx=10, pady=8, sticky="w")

# 第四行：转换按钮
btn_convert = tk.Button(root, text="转换", command=convert, width=12, font=("Arial", 10))
btn_convert.grid(row=3, column=0, columnspan=2, pady=12)

# 第五行：结果显示
label_result = tk.Label(root, text="结果: ", font=("Arial", 12, "bold"), fg="blue")
label_result.grid(row=4, column=0, columnspan=2, pady=8)

# 启动主循环
root.mainloop()