w = top . winfo_screenwidth () h = top . winfo_screenheight () top . geometry ( f " { w } x { h } +0+0" ) # 设置大小 top . overrideredirect ( True ) # 隐藏窗口栏 top . attributes ( '-alpha' , 0.01 ) # 设置透明度 最小0.01 设置为0 界面会消失掉 top . configure ( cursor = "crosshair" ) # 设置鼠标样式 top . bind ( "<Button-1>" , callback ) # 设置点击鼠标事件 top . mainloop ()

截屏获取颜色

在回调函数中进行截屏,在通过鼠标位置获取该坐标的颜色值。

    # 点击后的回调 截屏获取获取颜色值
    def callback(evt):
        top.destroy()
        img = ImageGrab.grab()
        img = img.resize((w, h))
        px = img.load()
        img.close()
        rgb = px[evt.x, evt.y]
        hex_color = rgb2hex(rgb)
        set_color(rgb, hex_color)

窗口大小和截屏的图片大小不一致

如果是win系统,设置了缩放与布局(通常是125%),会出现点击的颜色和返回的颜色不一致的问题,将比例改为100%就会正常取色。但是这样去改系统还是比较麻烦,其实可以在程序里面,将截取的图片,缩放到和窗口大小一样就行。

# 对截图大小重置为窗口大小。
img = img.resize((w, h))

取色笔是tk自带组件,调用相关的包就行了。

from tkinter import colorchooser
colorchooser.askcolor()

RGB转HEX

def rgb2hex(rgb):
    hex_color = "#" + hex(rgb[0])[2:].zfill(2) + hex(rgb[1])[2:].zfill(2) + hex(rgb[2])[2:].zfill(2)
    return hex_color.upper()

HEX转RGB

def hex2rgb(hex_color):
    h = hex_color
    rgb = (int((h[1:3]), 16), int((h[3:5]), 16), int((h[5:7]), 16))
    return rgb

主界面代码

主界面代码采用了tkinter布局助手生成的布局代码