import tkinter as tk
from math import gcd

class FractionSimplify:
    def __init__(self, root):
        self.root = root
        self.root.title("分数约分工具")
        self.root.geometry("420x260")

        # 分子输入
        tk.Label(root, text="分子：", font=("SimHei",14)).place(x=60, y=40)
        self.entry_top = tk.Entry(root, font=("SimHei",14), width=8)
        self.entry_top.place(x=120, y=40)

        # 分数线
        tk.Label(root, text="——", font=("SimHei",20)).place(x=220, y=38)

        # 分母输入
        tk.Label(root, text="分母：", font=("SimHei",14)).place(x=260, y=40)
        self.entry_bottom = tk.Entry(root, font=("SimHei",14), width=8)
        self.entry_bottom.place(x=320, y=40)

        # 计算按钮
        btn_calc = tk.Button(root, text="开始约分", command=self.simplify,
                             font=("SimHei",12), bg="#409EFF", fg="white")
        btn_calc.place(x=150, y=90, width=120)

        # 清空按钮
        btn_clear = tk.Button(root, text="清空", command=self.clear_all, font=("SimHei",12))
        btn_clear.place(x=280, y=90, width=80)

        # 结果显示
        tk.Label(root, text="化简结果：", font=("SimHei",14)).place(x=60, y=140)
        self.result_label = tk.Label(root, text="", font=("SimHei",14), fg="#222222")
        self.result_label.place(x=160, y=140)

        # 额外信息（最大公约数）
        self.info_label = tk.Label(root, text="", font=("SimHei",11), fg="#555555")
        self.info_label.place(x=60, y=180)

    def simplify(self):
        try:
            top = int(self.entry_top.get().strip())
            bottom = int(self.entry_bottom.get().strip())

            if bottom == 0:
                self.result_label.config(text="错误：分母不能为0！", fg="red")
                self.info_label.config(text="")
                return

            # 处理正负号
            sign = 1
            if bottom < 0:
                sign = -sign
                bottom = -bottom
            if top < 0:
                sign = -sign
                top = -top

            common = gcd(top, bottom)
            sim_top = sign * (top // common)
            sim_bottom = bottom // common

            if sim_bottom == 1:
                res_text = f"{sim_top}"
            else:
                res_text = f"{sim_top}/{sim_bottom}"

            self.result_label.config(text=res_text, fg="#0066cc")
            self.info_label.config(text=f"最大公约数 = {common}")

        except ValueError:
            self.result_label.config(text="请输入合法整数！", fg="red")
            self.info_label.config(text="")

    def clear_all(self):
        self.entry_top.delete(0, tk.END)
        self.entry_bottom.delete(0, tk.END)
        self.result_label.config(text="")
        self.info_label.config(text="")

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