首页 > 解决方案 > 如何正确转换列表的输出值以将它们用作函数内的 args?

问题描述

我正在尝试在 python 中编写一个脚本,该脚本在屏幕上搜索 RGB 中的特定颜色,获取像素坐标,然后将它们发送到单击函数以单击它。到目前为止,这是我的代码:

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
match = False

while(True):
    screen = ImageGrab.grab()
    found_pixels = []
    for i, pixel in enumerate(screen.getdata()):
        if pixel == color:
            match = True
            found_pixels.append(i)
            break
    else:
        match = False

    width, height = screen.size
    found_pixels_coords = [divmod(index, width) for index in found_pixels]

    if session == False and match == True:
        click(found_pixels_coords)
        print("Match_Found")
        session = True
    if session == True and match == False:
        session = False

如何转换输出founds_pixels_coords以在函数内使用它click(x,y)?我还将输出值反转,(y,x)而不是(x,y),我不明白为什么。

这是我的控制台输出,以防我完全错了:

Traceback (most recent call last):
  File "test2.py", line 28, in <module>
    click(found_pixels_coords)
TypeError: click() missing 1 required positional argument: 'y'

编辑: click(*found_pixels_coords[0])正如@martineau 所建议的,似乎解决了缺少的参数错误。我还通过定义 click(y,x). 但是,对此的任何适当解决方案将不胜感激。

标签: pythonpython-3.xwindowspython-imaging-library

解决方案


因为found_pixels_coords是一个列表(尽管它永远不会包含一组以上的坐标),所以这里是如何使用其中的一组(如果有匹配的话):


    .
    .
    .
    if session == False and match == True:
        click(*found_pixels_coords[0]) # <== Do it like this.
        print("Match_Found")
        session = True
    if session == True and match == False:
        session = False
    .
    .
    .


推荐阅读