import tkinter as tk
from tkinter import messagebox
from PIL import ImageGrab

class ScreenColorPicker:
    def __init__(self, root):
        self.root = root
        self.root.title("屏幕颜色识别取色器")
        self.root.geometry("480x320")

        self.color_box = tk.Label(root, bg="#ffffff", width=22, height=9)
        self.color_box.pack(pady=10)

        # 修复StringVar初始化问题
        self.hex_var = tk.StringVar(root)
        self.hex_var.set("HEX: #FFFFFF")

        self.rgb_var = tk.StringVar(root)
        self.rgb_var.set("RGB: (255,255,255)")

        tk.Label(root, textvariable=self.hex_var, font=("SimHei",12)).pack()
        tk.Label(root, textvariable=self.rgb_var, font=("SimHei",12)).pack()

        frame_btn = tk.Frame(root)
        frame_btn.pack(pady=12)
        tk.Button(frame_btn, text="获取鼠标当前位置颜色", command=self.get_mouse_color, font=("SimHei",11)).grid(row=0,column=0,padx=4)
        tk.Button(frame_btn, text="复制HEX", command=self.copy_hex).grid(row=0,column=1,padx=4)
        tk.Button(frame_btn, text="复制RGB", command=self.copy_rgb).grid(row=0,column=2,padx=4)

        self.hex = "#FFFFFF"
        self.rgb = (255,255,255)

    def get_mouse_color(self):
        # 获取鼠标坐标
        x = self.root.winfo_pointerx()
        y = self.root.winfo_pointery()
        screenshot = ImageGrab.grab()
        r,g,b = screenshot.getpixel((x, y))
        h = f"#{r:02X}{g:02X}{b:02X}"

        self.hex = h
        self.rgb = (r,g,b)

        self.color_box.config(bg=h)
        self.hex_var.set(f"HEX: {h}")
        self.rgb_var.set(f"RGB: ({r}, {g}, {b})")

    def copy_hex(self):
        self.root.clipboard_clear()
        self.root.clipboard_append(self.hex)
        messagebox.showinfo("复制成功", self.hex)

    def copy_rgb(self):
        txt = f"{self.rgb[0]}, {self.rgb[1]}, {self.rgb[2]}"
        self.root.clipboard_clear()
        self.root.clipboard_append(txt)
        messagebox.showinfo("复制成功", txt)

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