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

Python屏幕颜色点击脚本:如何将列表输出转为函数参数并修正坐标顺序

解决Python屏幕颜色识别与点击的两个问题

咱们一步步拆解你遇到的问题,给出更规范的解决方案:

1. 修复click()函数的参数传递错误

你碰到的TypeError: click() missing 1 required positional argument: 'y',是因为found_pixels_coords是一个装着坐标元组的列表,而click(x,y)需要两个独立的数值参数。

你用click(*found_pixels_coords[0])的思路是对的,这是Python的解包语法,能把元组里的元素分别传给函数参数。不过更严谨的写法可以提前提取坐标值,避免依赖列表索引:

if found_pixels:  # 先判断是否找到匹配像素
    # 先拿到原始的(y,x)(坐标顺序问题后面解决)
    y, x = divmod(found_pixels[0], width)
    click(x, y)  # 这里先临时交换,后面讲根源

2. 解决坐标(y,x)反转成(x,y)的问题

坐标顺序搞反的根源是ImageGrab.grab().getdata()的像素排列逻辑:

  • getdata()是按从上到下、从左到右的顺序遍历屏幕像素的
  • 每个像素的索引i计算公式为:i = y * 屏幕宽度 + x
  • 所以divmod(i, width)得到的结果是(y, x)(商是y坐标,余数是x坐标)

要得到正确的(x,y)顺序,有两种规范解决方式:

方式一:直接交换元组元素

在生成坐标列表时直接反转顺序:

found_pixels_coords = [(x, y) for y, x in [divmod(index, width) for index in found_pixels]]

或者提取单个坐标时交换:

if found_pixels:
    y, x = divmod(found_pixels[0], width)
    correct_x, correct_y = x, y
    click(correct_x, correct_y)

方式二:遍历屏幕时直接记录(x,y)(更高效清晰)

与其先拿索引再转换坐标,不如直接遍历屏幕的x、y轴,这样能直接拿到正确的坐标,还能简化逻辑:

while(True):
    screen = ImageGrab.grab()
    width, height = screen.size
    match = False
    target_x, target_y = -1, -1

    # 直接遍历x、y坐标寻找匹配颜色
    for y in range(height):
        for x in range(width):
            if screen.getpixel((x, y)) == color:
                target_x, target_y = x, y
                match = True
                break  # 找到第一个匹配就退出内层循环
        if match:
            break  # 退出外层循环

    # 点击逻辑
    if not session and match:
        click(target_x, target_y)
        print("Match_Found")
        session = True
    if session and not match:
        session = False

优化后的完整代码

整合所有修正后的最终版本:

from PIL import ImageGrab
import win32api, win32con

def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

color = (10,196,182)
session = False

while(True):
    screen = ImageGrab.grab()
    width, height = screen.size
    match = False
    target_x, target_y = -1, -1

    # 遍历屏幕坐标寻找匹配颜色
    for y in range(height):
        for x in range(width):
            if screen.getpixel((x, y)) == color:
                target_x, target_y = x, y
                match = True
                break
        if match:
            break

    # 点击状态逻辑
    if not session and match:
        click(target_x, target_y)
        print("Match_Found")
        session = True
    if session and not match:
        session = False

这个版本既解决了参数传递和坐标反转的问题,逻辑也更清晰易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:52:10