如何让pyautogui的截图功能在mac上运行?

问题描述

霸王龙游戏:http://www.trex-game.skipser.com/

我是 Python 新手。现在我正在学习编写自动机脚本。

我曾多次尝试按照 YouTube 上的说明更改代码。 (“使用 Python 在任何游戏中作弊 | Python 和 pyautogui 教程 2020 | 为初学者学习 Python”,作者:Davidd That's Me:https://www.youtube.com/watch?v=xYymkeNh2lE),但失败了。

YouTube 上的代码在 Windows 上,但我的是在 MacOS 上。

pyobjc 和 pyobjc-core 都安装了。 (MacOS)

使用“Shift-Command-4”(MacOS) 获取屏幕坐标(x 像素、y 像素)

pyautogui.moveto(x,y) : 鼠标指针正确移动到“Shift-Command-4”(屏幕坐标)读取的指定位置。

但是……

pyautogui.screenshot(region = (left,top,width,height) : 我发现要插入“left”(以及其他参数)的整数必须乘以 2 才能正确获得所需区域的屏幕截图。

我想知道...

  1. 为什么输入到截图函数pyautogui.screenshot())中的坐标与从屏幕坐标中获取的坐标不同。还有

  2. pyautogui 库可能存在不稳定问题吗? 我尝试多次运行脚本,有时screenshot()函数运行不正常,例如,从函数获取的图像发生变化而屏幕保持不变,或者从getcolors()函数返回的值为零而图片是白色的。

下面是我的代码

任何帮助将不胜感激。

'''

from PIL import ImageGrab   # The ImageGrab module can be used to copy the contents of the screen
from PIL import ImageOps    # Analyze it to find out whether it's gray or white
import pyautogui            # Control mouse and keyboard
import time
from numpy import *

replaybtn = (640,530)
dianosaur = (407,540)

# i for debugging
i = 0

def restartGame():
    pyautogui.moveto(replaybtn,duration=0.5)
    pyautogui.click(replaybtn)
    print("I just clicked play buttom.")

def image_grab():
    global i

    # (left_x,top_y,high)
    # Box = (2*dianosaur[0]+10,2*dinosaur[1],2*dianosaur[0]+50,2*dianosaur[1]+10)
    # image = ImageGrab.grab(Box) 

    # region = (left_x,high)
    image = pyautogui.screenshot(region=(2*dianosaur[0]+10,2*dianosaur[1],50,10))
    
    # For debugging
    # image.save(str(i) + '.png')
    
    grayImage = ImageOps.grayscale(image)
    a = array(grayImage.getcolors())

    # For debugging
    # White screen a.sum =  1247
    print(a)              
    print('a.sum = ',a.sum())
    if (a.sum() != 1247):
        image.save(str(i) + '.png')
    i+=1

    return a.sum()

def pressspace():
    time.sleep(0.1)
    pyautogui.keyDown('space')
    print("Space pressed.")
    

time.sleep(3)
restartGame()

try:                    
    while True:
        image_grab()
        if (image_grab() != 1247):
            pressspace()    
            time.sleep(0.1) 
except KeyboardInterrupt:
    print("\nDone...")        

'''

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...