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

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

def get_mouse_pos():
    return root.winfo_pointerx(), root.winfo_pointery()

def get_color():
    try:
        x, y = get_mouse_pos()
        # 截取鼠标单个像素
        screen = ImageGrab.grab(bbox=(x, y, x+1, y+1))
        r, g, b = screen.getpixel((0, 0))
        
        hex_color = rgb_to_hex(r, g, b)
        label_rgb.config(text=f"RGB: ({r}, {g}, {b})")
        label_hex.config(text=f"HEX: {hex_color}")
        color_box.config(bg=hex_color)

        global current_rgb, current_hex
        current_rgb = f"({r}, {g}, {b})"
        current_hex = hex_color
    except Exception as e:
        messagebox.showerror("错误", str(e))

def copy_rgb():
    root.clipboard_clear()
    root.clipboard_append(current_rgb)
    messagebox.showinfo("提示", "RGB已复制到剪贴板！")

def copy_hex():
    root.clipboard_clear()
    root.clipboard_append(current_hex)
    messagebox.showinfo("提示", "HEX已复制到剪贴板！")

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

root = tk.Tk()
root.title("屏幕颜色拾取器")
root.geometry("360x240")
root.resizable(False, False)

color_box = tk.Label(root, bg="#000000", width=20, height=8, relief=tk.SUNKEN)
color_box.pack(pady=12)

label_rgb = ttk.Label(root, text="RGB: (0, 0, 0)", font=("Arial", 12))
label_rgb.pack()
label_hex = ttk.Label(root, text="HEX: #000000", font=("Arial", 12))
label_hex.pack(pady=4)

frame_btn = ttk.Frame(root)
frame_btn.pack(pady=10)

ttk.Button(frame_btn, text="拾取鼠标位置颜色", command=get_color).grid(row=0, column=0, padx=5)
ttk.Button(frame_btn, text="复制RGB", command=copy_rgb).grid(row=0, column=1, padx=5)
ttk.Button(frame_btn, text="复制HEX", command=copy_hex).grid(row=0, column=2, padx=5)

root.mainloop()