import random
import tkinter as tk

# 颜色数据库
color_dict = {
    "红色": (255, 0, 0),
    "绿色": (0, 255, 0),
    "蓝色": (0, 0, 255),
    "黄色": (255, 255, 0),
    "紫色": (128, 0, 128),
    "黑色": (0, 0, 0),
    "白色": (255, 255, 255),
    "橙色": (255, 165, 0),
    "青色": (0, 255, 255),
    "粉色": (255, 192, 203),
    "灰色": (128, 128, 128),
    "棕色": (139, 69, 19)
}

class ColorPracticeGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("配色视觉练习工具")
        self.score = 0
        self.count = 0
        self.color_items = list(color_dict.items())
        self.current_color_name = ""
        self.current_rgb = (0,0,0)

        # 界面布局
        # 色块画布
        self.canvas = tk.Canvas(root, width=300, height=200, bg="white")
        self.canvas.pack(pady=10)
        self.color_rect = self.canvas.create_rectangle(50, 20, 250, 180, fill="#000000")

        # RGB提示文字
        self.rgb_label = tk.Label(root, text="RGB: (0, 0, 0)", font=("Arial",14))
        self.rgb_label.pack()

        # 输入框
        self.entry = tk.Entry(root, font=("Arial",14), width=15)
        self.entry.pack(pady=8)

        # 按钮区域
        frame_btn = tk.Frame(root)
        frame_btn.pack(pady=5)
        tk.Button(frame_btn, text="提交答案", command=self.check_ans).grid(row=0,column=0,padx=5)
        tk.Button(frame_btn, text="下一题", command=self.next_color).grid(row=0,column=1,padx=5)

        # 得分提示
        self.result_label = tk.Label(root, text="得分：0 / 0", font=("Arial",13))
        self.result_label.pack(pady=10)

        # 加载第一题
        self.next_color()

    # RGB转十六进制颜色码
    def rgb2hex(self, r, g, b):
        return f"#{r:02x}{g:02x}{b:02x}"

    # 切换随机颜色
    def next_color(self):
        self.current_color_name, self.current_rgb = random.choice(self.color_items)
        r,g,b = self.current_rgb
        hex_color = self.rgb2hex(r,g,b)
        self.canvas.itemconfig(self.color_rect, fill=hex_color)
        self.rgb_label.config(text=f"RGB: ({r}, {g}, {b})")
        self.entry.delete(0, tk.END)

    # 核对答案
    def check_ans(self):
        user_ans = self.entry.get().strip()
        self.count += 1
        if user_ans == self.current_color_name:
            self.score += 1
            self.result_label.config(text=f"✅ 正确！得分：{self.score} / {self.count}")
        else:
            self.result_label.config(text=f"❌ 错误，正确：{self.current_color_name}  | {self.score}/{self.count}")

if __name__ == "__main__":
    window = tk.Tk()
    app = ColorPracticeGUI(window)
    window.mainloop()