import tkinter as tk
from tkinter import messagebox


def c_to_f():
    """摄氏度转华氏度"""
    try:
        c = float(entry_c.get())
        f = c * 9 / 5 + 32
        var_f.set(f"{f:.2f}")
    except ValueError:
        messagebox.showerror("输入错误", "请输入有效的数字！")


def f_to_c():
    """华氏度转摄氏度"""
    try:
        f = float(entry_f.get())
        c = (f - 32) * 5 / 9
        var_c.set(f"{c:.2f}")
    except ValueError:
        messagebox.showerror("输入错误", "请输入有效的数字！")


def clear_all():
    """清空所有输入输出"""
    entry_c.delete(0, tk.END)
    entry_f.delete(0, tk.END)
    var_c.set("")
    var_f.set("")


# 创建主窗口
root = tk.Tk()
root.title("温度单位转换器")
root.geometry("420x220")  # 窗口大小
root.resizable(False, False)

# 变量
var_c = tk.StringVar()
var_f = tk.StringVar()

# 布局组件
# 摄氏度区域
label_c = tk.Label(root, text="摄氏度(℃):", font=("微软雅黑",12))
label_c.place(x=40, y=40)
entry_c = tk.Entry(root, textvariable=var_c, font=("微软雅黑",12), width=12)
entry_c.place(x=140, y=40)

btn_c2f = tk.Button(root, text="→转华氏度", command=c_to_f, font=("微软雅黑",10))
btn_c2f.place(x=270, y=38)

# 华氏度区域
label_f = tk.Label(root, text="华氏度(℉):", font=("微软雅黑",12))
label_f.place(x=40, y=90)
entry_f = tk.Entry(root, textvariable=var_f, font=("微软雅黑",12), width=12)
entry_f.place(x=140, y=90)

btn_f2c = tk.Button(root, text="→转摄氏度", command=f_to_c, font=("微软雅黑",10))
btn_f2c.place(x=270, y=88)

# 清空按钮
btn_clear = tk.Button(root, text="清空全部", command=clear_all, font=("微软雅黑",11), bg="#eeeeee")
btn_clear.place(x=150, y=140)

# 底部说明
tip_label = tk.Label(root, text="公式：℉ = ℃ × 9/5 +32", fg="#555555", font=("微软雅黑",9))
tip_label.place(x=110, y=180)

root.mainloop()
