import tkinter as tk
from tkinter import ttk, messagebox
import math

class TemperatureConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("温度单位转换器")
        self.root.geometry("500x550")
        self.root.configure(bg='#f5f7fa')
        self.root.resizable(False, False)
        
        # 设置颜色主题
        self.colors = {
            'bg': '#f5f7fa',
            'card_bg': '#ffffff',
            'primary': '#3498db',
            'secondary': '#2ecc71',
            'danger': '#e74c3c',
            'text': '#2c3e50',
            'muted': '#7f8c8d'
        }
        
        # 温度单位信息
        self.temp_units = {
            'C': {'name': '摄氏度', 'symbol': '°C', 'full_name': '摄氏度 (°C)'},
            'F': {'name': '华氏度', 'symbol': '°F', 'full_name': '华氏度 (°F)'},
            'K': {'name': '开尔文', 'symbol': 'K', 'full_name': '开尔文 (K)'},
            'R': {'name': '兰金度', 'symbol': '°R', 'full_name': '兰金度 (°R)'}
        }
        
        # 温度描述
        self.temp_descriptions = {
            'freezing': ('❄️ 冰点', '#3498db'),
            'cold': ('🥶 寒冷', '#2980b9'),
            'cool': ('😊 凉爽', '#3498db'),
            'mild': ('😌 温和', '#2ecc71'),
            'warm': ('😊 温暖', '#e67e22'),
            'hot': ('🥵 炎热', '#e74c3c'),
            'boiling': ('🔥 沸点', '#c0392b')
        }
        
        # 创建界面
        self.setup_ui()
        
        # 绑定事件
        self.setup_bindings()
        
        # 初始转换
        self.convert_temperature()
    
    def setup_ui(self):
        """设置用户界面"""
        # 标题区域
        title_frame = tk.Frame(self.root, bg=self.colors['primary'], height=80)
        title_frame.pack(fill=tk.X)
        title_frame.pack_propagate(False)
        
        title_label = tk.Label(
            title_frame,
            text="🌡️ 温度单位转换器",
            font=('Microsoft YaHei', 18, 'bold'),
            fg='white',
            bg=self.colors['primary']
        )
        title_label.pack(expand=True)
        
        # 主内容区域
        main_frame = tk.Frame(self.root, bg=self.colors['bg'], padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 输入卡片
        input_card = tk.Frame(main_frame, bg=self.colors['card_bg'], padx=20, pady=20)
        input_card.pack(fill=tk.X, pady=(0, 15))
        
        # 输入标签
        input_label = tk.Label(
            input_card,
            text="输入温度值:",
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg']
        )
        input_label.pack(anchor=tk.W, pady=(0, 10))
        
        # 输入框和单位选择
        input_row = tk.Frame(input_card, bg=self.colors['card_bg'])
        input_row.pack(fill=tk.X)
        
        # 输入框
        self.temp_var = tk.StringVar(value="0")
        self.temp_entry = tk.Entry(
            input_row,
            textvariable=self.temp_var,
            font=('Microsoft YaHei', 16),
            width=15,
            justify='center',
            bd=2,
            relief=tk.SOLID
        )
        self.temp_entry.pack(side=tk.LEFT, padx=(0, 10))
        
        # 从单位选择
        self.from_unit = ttk.Combobox(
            input_row,
            values=[unit['full_name'] for unit in self.temp_units.values()],
            state='readonly',
            width=20,
            font=('Microsoft YaHei', 12)
        )
        self.from_unit.set(self.temp_units['C']['full_name'])
        self.from_unit.pack(side=tk.LEFT, padx=(0, 20))
        
        # 转换按钮
        self.convert_btn = tk.Button(
            input_row,
            text="转换 🔄",
            command=self.convert_temperature,
            font=('Microsoft YaHei', 12, 'bold'),
            bg=self.colors['primary'],
            fg='white',
            activebackground='#2980b9',
            activeforeground='white',
            bd=0,
            padx=20,
            pady=8,
            cursor='hand2'
        )
        self.convert_btn.pack(side=tk.LEFT)
        
        # 交换按钮
        self.swap_btn = tk.Button(
            input_row,
            text="交换 ⭮",
            command=self.swap_units,
            font=('Microsoft YaHei', 10),
            bg=self.colors['secondary'],
            fg='white',
            activebackground='#27ae60',
            activeforeground='white',
            bd=0,
            padx=10,
            pady=5,
            cursor='hand2'
        )
        self.swap_btn.pack(side=tk.LEFT, padx=(10, 0))
        
        # 转换结果区域
        result_card = tk.Frame(main_frame, bg=self.colors['card_bg'], padx=20, pady=20)
        result_card.pack(fill=tk.BOTH, expand=True)
        
        result_label = tk.Label(
            result_card,
            text="转换结果:",
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg']
        )
        result_label.pack(anchor=tk.W, pady=(0, 10))
        
        # 结果显示表格
        table_frame = tk.Frame(result_card, bg=self.colors['card_bg'])
        table_frame.pack(fill=tk.BOTH, expand=True)
        
        # 表头
        headers = ['单位', '符号', '温度值', '描述']
        for i, header in enumerate(headers):
            header_label = tk.Label(
                table_frame,
                text=header,
                font=('Microsoft YaHei', 10, 'bold'),
                fg=self.colors['primary'],
                bg=self.colors['card_bg'],
                padx=10,
                pady=8
            )
            header_label.grid(row=0, column=i, sticky='ew', padx=1, pady=1)
        
        # 创建表格行
        self.result_labels = {}
        for idx, unit_key in enumerate(self.temp_units.keys()):
            unit_info = self.temp_units[unit_key]
            
            # 单位名称
            name_label = tk.Label(
                table_frame,
                text=unit_info['name'],
                font=('Microsoft YaHei', 10),
                bg='#f8f9fa',
                padx=10,
                pady=8
            )
            name_label.grid(row=idx+1, column=0, sticky='ew', padx=1, pady=1)
            
            # 单位符号
            symbol_label = tk.Label(
                table_frame,
                text=unit_info['symbol'],
                font=('Microsoft YaHei', 10),
                bg='#f8f9fa',
                padx=10,
                pady=8
            )
            symbol_label.grid(row=idx+1, column=1, sticky='ew', padx=1, pady=1)
            
            # 温度值
            value_label = tk.Label(
                table_frame,
                text="0.00",
                font=('Microsoft YaHei', 10, 'bold'),
                bg='#f8f9fa',
                padx=10,
                pady=8
            )
            value_label.grid(row=idx+1, column=2, sticky='ew', padx=1, pady=1)
            
            # 温度描述
            desc_label = tk.Label(
                table_frame,
                text="-",
                font=('Microsoft YaHei', 9),
                bg='#f8f9fa',
                padx=10,
                pady=8
            )
            desc_label.grid(row=idx+1, column=3, sticky='ew', padx=1, pady=1)
            
            self.result_labels[unit_key] = {
                'value': value_label,
                'description': desc_label
            }
        
        # 设置列权重
        for i in range(4):
            table_frame.grid_columnconfigure(i, weight=1)
        
        # 温度参考表
        self.setup_reference_table(main_frame)
        
        # 状态栏
        self.setup_status_bar()
    
    def setup_reference_table(self, parent):
        """设置温度参考表"""
        ref_card = tk.Frame(parent, bg=self.colors['card_bg'], padx=20, pady=15)
        ref_card.pack(fill=tk.X, pady=(15, 0))
        
        ref_label = tk.Label(
            ref_card,
            text="🌡️ 常见温度参考:",
            font=('Microsoft YaHei', 10, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg']
        )
        ref_label.pack(anchor=tk.W, pady=(0, 10))
        
        # 常见温度点
        common_temps = [
            ("绝对零度", -273.15, -459.67, 0, 0, 'freezing'),
            ("水冰点", 0, 32, 273.15, 491.67, 'freezing'),
            ("人体温度", 37, 98.6, 310.15, 558.27, 'mild'),
            ("水沸点", 100, 212, 373.15, 671.67, 'boiling')
        ]
        
        for i, (name, c, f, k, r, temp_type) in enumerate(common_temps):
            frame = tk.Frame(ref_card, bg=self.colors['card_bg'])
            frame.pack(fill=tk.X, pady=2)
            
            # 温度描述
            desc_text, desc_color = self.temp_descriptions[temp_type]
            name_label = tk.Label(
                frame,
                text=f"{name} {desc_text}",
                font=('Microsoft YaHei', 9),
                fg=desc_color,
                bg=self.colors['card_bg'],
                width=15,
                anchor='w'
            )
            name_label.pack(side=tk.LEFT)
            
            # 各单位的温度值
            temps_text = f"C: {c}°  |  F: {f}°  |  K: {k}  |  R: {r}°"
            temps_label = tk.Label(
                frame,
                text=temps_text,
                font=('Microsoft YaHei', 8),
                fg=self.colors['muted'],
                bg=self.colors['card_bg']
            )
            temps_label.pack(side=tk.LEFT, padx=(10, 0))
            
            # 快速设置按钮
            def make_set_temp(c_temp=c):
                return lambda: self.set_temperature(c_temp, 'C')
            
            set_btn = tk.Button(
                frame,
                text="使用",
                command=make_set_temp(),
                font=('Microsoft YaHei', 8),
                bg='#ecf0f1',
                fg=self.colors['text'],
                bd=0,
                padx=5,
                pady=2,
                cursor='hand2'
            )
            set_btn.pack(side=tk.RIGHT)
    
    def setup_status_bar(self):
        """设置状态栏"""
        status_bar = tk.Frame(self.root, bg='#2c3e50', height=30)
        status_bar.pack(fill=tk.X, side=tk.BOTTOM)
        status_bar.pack_propagate(False)
        
        self.status_var = tk.StringVar(value="就绪 | 输入温度值并选择单位进行转换")
        status_label = tk.Label(
            status_bar,
            textvariable=self.status_var,
            font=('Microsoft YaHei', 9),
            fg='white',
            bg='#2c3e50',
            anchor=tk.W,
            padx=10
        )
        status_label.pack(fill=tk.X)
    
    def setup_bindings(self):
        """绑定事件"""
        self.temp_entry.bind('<Return>', lambda e: self.convert_temperature())
        self.temp_entry.bind('<KeyRelease>', lambda e: self.convert_temperature())
        self.from_unit.bind('<<ComboboxSelected>>', lambda e: self.convert_temperature())
    
    def get_current_unit(self):
        """获取当前选择的单位"""
        full_name = self.from_unit.get()
        for key, unit_info in self.temp_units.items():
            if unit_info['full_name'] == full_name:
                return key
        return 'C'  # 默认返回摄氏度
    
    def celsius_to_other(self, celsius):
        """摄氏度转换为其他单位"""
        fahrenheit = (celsius * 9/5) + 32
        kelvin = celsius + 273.15
        rankine = (celsius + 273.15) * 9/5
        return {'C': celsius, 'F': fahrenheit, 'K': kelvin, 'R': rankine}
    
    def fahrenheit_to_other(self, fahrenheit):
        """华氏度转换为其他单位"""
        celsius = (fahrenheit - 32) * 5/9
        kelvin = (fahrenheit + 459.67) * 5/9
        rankine = fahrenheit + 459.67
        return {'C': celsius, 'F': fahrenheit, 'K': kelvin, 'R': rankine}
    
    def kelvin_to_other(self, kelvin):
        """开尔文转换为其他单位"""
        celsius = kelvin - 273.15
        fahrenheit = (kelvin * 9/5) - 459.67
        rankine = kelvin * 9/5
        return {'C': celsius, 'F': fahrenheit, 'K': kelvin, 'R': rankine}
    
    def rankine_to_other(self, rankine):
        """兰金度转换为其他单位"""
        kelvin = rankine * 5/9
        celsius = (rankine - 491.67) * 5/9
        fahrenheit = rankine - 459.67
        return {'C': celsius, 'F': fahrenheit, 'K': kelvin, 'R': rankine}
    
    def get_temperature_description(self, temp_c):
        """根据摄氏度获取温度描述"""
        if temp_c < -20:
            return self.temp_descriptions['freezing']
        elif temp_c < 0:
            return self.temp_descriptions['cold']
        elif temp_c < 10:
            return self.temp_descriptions['cool']
        elif temp_c < 20:
            return self.temp_descriptions['mild']
        elif temp_c < 30:
            return self.temp_descriptions['warm']
        elif temp_c < 80:
            return self.temp_descriptions['hot']
        else:
            return self.temp_descriptions['boiling']
    
    def set_temperature(self, value, unit_key='C'):
        """设置温度值"""
        self.temp_var.set(str(value))
        
        # 设置对应的单位
        unit_info = self.temp_units[unit_key]
        self.from_unit.set(unit_info['full_name'])
        
        # 执行转换
        self.convert_temperature()
        
        # 更新状态
        self.status_var.set(f"已设置: {value} {unit_info['symbol']}")
    
    def swap_units(self):
        """交换输入和输出的主单位"""
        current_from = self.get_current_unit()
        
        # 找到不是当前单位的其他单位
        other_units = [key for key in self.temp_units.keys() if key != current_from]
        if other_units:
            new_unit = other_units[0]  # 选择第一个其他单位
            unit_info = self.temp_units[new_unit]
            self.from_unit.set(unit_info['full_name'])
            self.convert_temperature()
    
    def convert_temperature(self, event=None):
        """执行温度转换"""
        try:
            # 获取输入
            temp_str = self.temp_var.get().strip()
            if not temp_str:
                return
            
            try:
                temperature = float(temp_str)
            except ValueError:
                if temp_str.startswith('-') and temp_str[1:].replace('.', '', 1).isdigit():
                    temperature = float(temp_str)
                else:
                    return
            
            from_unit = self.get_current_unit()
            
            # 根据输入单位进行转换
            if from_unit == 'C':
                results = self.celsius_to_other(temperature)
            elif from_unit == 'F':
                results = self.fahrenheit_to_other(temperature)
            elif from_unit == 'K':
                results = self.kelvin_to_other(temperature)
            elif from_unit == 'R':
                results = self.rankine_to_other(temperature)
            else:
                return
            
            # 更新结果表格
            for unit_key, temp in results.items():
                # 格式化温度值
                if abs(temp) < 0.01 and temp != 0:
                    formatted_temp = f"{temp:.2e}"
                else:
                    formatted_temp = f"{temp:.2f}"
                
                # 更新数值
                value_label = self.result_labels[unit_key]['value']
                value_label.config(text=formatted_temp)
                
                # 获取并更新温度描述
                if unit_key == 'C':
                    temp_c = temp
                elif unit_key == 'F':
                    temp_c = (temp - 32) * 5/9
                elif unit_key == 'K':
                    temp_c = temp - 273.15
                else:  # R
                    temp_c = (temp - 491.67) * 5/9
                
                desc_text, desc_color = self.get_temperature_description(temp_c)
                desc_label = self.result_labels[unit_key]['description']
                desc_label.config(text=desc_text, fg=desc_color)
            
            # 更新状态
            input_unit = self.temp_units[from_unit]
            self.status_var.set(f"已转换: {temperature} {input_unit['symbol']} 到其他单位")
            
        except Exception as e:
            self.status_var.set(f"转换错误: {str(e)}")
    
    def clear_input(self):
        """清空输入"""
        self.temp_var.set("")
        for unit_key in self.temp_units.keys():
            self.result_labels[unit_key]['value'].config(text="0.00")
            self.result_labels[unit_key]['description'].config(text="-", fg='black')
        self.status_var.set("已清空 | 输入新的温度值进行转换")

def main():
    root = tk.Tk()
    
    # 设置窗口图标
    try:
        root.iconbitmap(default='icon.ico')
    except:
        pass
    
    # 设置窗口居中
    window_width = 500
    window_height = 550
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    center_x = int(screen_width/2 - window_width/2)
    center_y = int(screen_height/2 - window_height/2)
    root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
    
    # 创建应用
    app = TemperatureConverter(root)
    
    # 运行主循环
    root.mainloop()

if __name__ == "__main__":
    main()