import tkinter as tk
from tkinter import ttk, messagebox

class TempConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("温度单位转换器")
        self.root.geometry("430x270")
        self.root.resizable(False, False)

        # 变量
        self.input_var = tk.StringVar()
        self.result_var = tk.StringVar()
        temp_units = ["摄氏度(℃)", "华氏度(℉)", "开尔文(K)"]

        # 输入区域
        ttk.Label(root, text="输入温度：", font=("微软雅黑", 11)).place(x=30, y=30)
        entry_input = ttk.Entry(root, textvariable=self.input_var, font=("微软雅黑", 12), width=20)
        entry_input.place(x=110, y=30)

        # 原始单位
        ttk.Label(root, text="原始单位：", font=("微软雅黑", 11)).place(x=30, y=80)
        self.combo_from = ttk.Combobox(root, values=temp_units, font=("微软雅黑", 10), width=18)
        self.combo_from.place(x=110, y=80)
        self.combo_from.current(0)

        # 目标单位
        ttk.Label(root, text="转换单位：", font=("微软雅黑", 11)).place(x=30, y=130)
        self.combo_to = ttk.Combobox(root, values=temp_units, font=("微软雅黑", 10), width=18)
        self.combo_to.place(x=110, y=130)
        self.combo_to.current(1)

        # 转换按钮
        btn_convert = ttk.Button(root, text="开始转换", command=self.convert_temp, width=12)
        btn_convert.place(x=145, y=180)

        # 结果展示
        ttk.Label(root, text="转换结果：", font=("微软雅黑", 11)).place(x=30, y=230)
        label_result = ttk.Label(root, textvariable=self.result_var, font=("微软雅黑", 12, "bold"), foreground="#c82423")
        label_result.place(x=110, y=230)

    def convert_temp(self):
        try:
            value = float(self.input_var.get())
            unit_from = self.combo_from.get()
            unit_to = self.combo_to.get()

            # 统一先转为摄氏度作为中间量
            celsius = 0
            if unit_from == "摄氏度(℃)":
                celsius = value
            elif unit_from == "华氏度(℉)":
                celsius = (value - 32) * 5 / 9
            elif unit_from == "开尔文(K)":
                celsius = value - 273.15

            # 摄氏度转为目标单位
            res = 0
            if unit_to == "摄氏度(℃)":
                res = celsius
            elif unit_to == "华氏度(℉)":
                res = celsius * 9 / 5 + 32
            elif unit_to == "开尔文(K)":
                res = celsius + 273.15

            self.result_var.set(f"{res:.2f} {unit_to}")

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

if __name__ == "__main__":
    win = tk.Tk()
    app = TempConverter(win)
    win.mainloop()