import tkinter as tk
from tkinter import ttk
from PIL import ImageGrab
import pyperclip

class ColorPickerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("颜色识别取色器")
        self.root.geometry("420x260")
        self.root.resizable(False, False)

        # 颜色预览块
        self.color_preview = tk.Label(root, bg="#000000", width=20, height=8, relief="solid")
        self.color_preview.pack(pady=10)

        frame = ttk.Frame(root)
        frame.pack()

        ttk.Label(frame, text="RGB: ").grid(row=0, column=0, sticky="w")
        self.rgb_text = ttk.Label(frame, text="(0, 0, 0)")
        self.rgb_text.grid(row=0, column=1, padx=10)

        ttk.Label(frame, text="HEX: ").grid(row=1, column=0, sticky="w")
        self.hex_text = ttk.Label(frame, text="#000000")
        self.hex_text.grid(row=1, column=1, padx=10)

        btn_frame = ttk.Frame(root)
        btn_frame.pack(pady=12)
        ttk.Button(btn_frame, text="复制HEX", command=self.copy_hex).grid(row=0, column=0, padx=6)
        ttk.Button(btn_frame, text="复制RGB", command=self.copy_rgb).grid(row=0, column=1, padx=6)

        self.current_rgb = (0, 0, 0)
        self.current_hex = "#000000"

        self.update_color()

    def rgb_to_hex(self, r, g, b):
        return f"#{r:02X}{g:02X}{b:02X}"

    def update_color(self):
        try:
            # 获取鼠标位置
            x = self.root.winfo_pointerx()
            y = self.root.winfo_pointery()
            # 截取鼠标单个像素
            screen = ImageGrab.grab(bbox=(x, y, x+1, y+1))
            r, g, b = screen.getpixel((0, 0))

            self.current_rgb = (r, g, b)
            self.current_hex = self.rgb_to_hex(r, g, b)

            self.color_preview.config(bg=self.current_hex)
            self.rgb_text.config(text=f"({r}, {g}, {b})")
            self.hex_text.config(text=self.current_hex)
        except Exception:
            pass

        self.root.after(40, self.update_color)

    def copy_hex(self):
        pyperclip.copy(self.current_hex)

    def copy_rgb(self):
        pyperclip.copy(str(self.current_rgb))

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