You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.9开发取色器遇TypeError:需整数参数却传入浮点数求解决

解决ImageGrab.grab()的TypeError:整数参数预期,得到浮点数

错误原因:pynput返回的鼠标点击坐标是浮点数,但PIL的ImageGrab.grab()要求bbox参数的所有值必须是整数,因此触发类型错误。

修复方法

在checkColor函数中,先将传入的x、y坐标转换为整数,再构建bbox:

def checkColor(x,y):
    # 将浮点数坐标转为整数
    x_int = int(x)
    y_int = int(y)
    bbox = (x_int, y_int, x_int + 1, y_int + 1)
    im = ImageGrab.grab(bbox=bbox)
    rgbim = im.convert('RGB')
    r,g,b = rgbim.getpixel((0,0))
    print(f'COLOR: rgb{(r,g,b)} | HEX #{getHex((r,g,b))}')

完整修正代码

from pynput import keyboard
from pynput import mouse
from PIL import Image, ImageGrab

def getHex(rgb):
    return '%02X%02X%02X'%rgb


def checkColor(x,y):
    # 转换坐标为整数,适配ImageGrab的参数要求
    x_int = int(x)
    y_int = int(y)
    bbox = (x_int, y_int, x_int + 1, y_int + 1)
    im = ImageGrab.grab(bbox=bbox)
    rgbim = im.convert('RGB')
    r,g,b = rgbim.getpixel((0,0))
    print(f'COLOR: rgb{(r,g,b)} | HEX #{getHex((r,g,b))}')
    
   
def onClick(x,y, button, pressed):
    if pressed and button == mouse.Button.left:
        checkColor(x,y)

def onRel(key):
    if key == keyboard.Key.esc:
        mlstnr.stop()
        return False

if __name__ == '__main__':
    with keyboard.Listener(on_release = onRel) as klstnr:
        with mouse.Listener(on_click = onClick) as mlstnr:
            klstnr.join()
            mlstnr.join()

补充说明:高DPI显示器(比如Mac的Retina屏幕)会对系统坐标做缩放,导致pynput获取的坐标带有小数,转换为整数后就能匹配ImageGrab对像素坐标的整数要求。

内容的提问来源于stack exchange,提问作者jasmine zhao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 08:05:22