PyAutoGui 和 PyScreeze

问题描述 投票:0回答:1

我编写了一个简单的 Osu!机器人,但它不起作用。在我打开(全屏)osu 之前,我不会收到任何错误。我尝试用管理员身份从cmd运行它,但它不起作用。我收到此错误:

Traceback (most recent call last):
  File "C:/Users/Kris/PycharmProjects/OsuBot/venv/drums.py", line 7, in <module>
    if pyautogui.pixel(609, 440)[0] == 235:
  File "C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\pyscreeze\__init__.py", line 584, in pixel
    return (r, g, b)
  File "C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\contextlib.py", line 120, in __exit__
    next(self.gen)
  File "C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\pyscreeze\__init__.py", line 113, in __win32_openDC
    raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0

Process finished with exit code 1

我在从 IDLE、cmd 和 PyCharm 运行时收到错误。

这是我的代码:

import pyautogui
import keyboard
import time

while 1:
    if pyautogui.pixel(609, 440)[0] == 235:
        keyboard.press('x')
        time.sleep(0.1)
        keyboard.release('x')
    if pyautogui.pixel(609, 440)[0] == 67:
        keyboard.press('z')
        time.sleep(0.1)
        keyboard.release('z')
    time.sleep(0.01)

# X:  609 Y:  440 RGB: ( 32,  99, 222)
# RED = X: 1534 Y:  485 RGB: (235,  69,  44)
# BLUE = X: 1138 Y:  459 RGB: ( 67, 142, 172)

提前致谢。

python python-3.x windows pyautogui
1个回答
0
投票

看起来

pyautogui
在像素识别方面存在一些问题,因为我也尝试过
pyautogui.pixel()
并且我似乎得到了相同的
OSError: windll.user32.ReleaseDC failed : return 0
但是由于某种原因它工作了一半的时间并且我让代码正常运行。但不知道为什么,除了连续多次重新运行程序直到它起作用之外,我没有做任何事情。

您可以使用

pillow
尝试使用
pip install pillow
库,它具有
getpixel()
功能。您必须先截取屏幕截图,但幸运的是
pyautogui
已经涵盖了这一点:

from PIL import Image
import pyautogui as py

py.screenshot('file.png')

img = Image.open('file.png')
print(img.getpixel((180, 90)))

我看到您也在使用

keyboard
库,但老实说,您可以只使用
pyautogui
来实现,然后您就不需要导入额外的库。

最终代码

import time
from PIL import Image
import pyautogui as py

while 1:

    py.screenshot('file.png')
    img = Image.open('file.png')
    
    if img.getpixel((609, 440))[0] == 235:
        py.press('x')
    if img.getpixel((609, 440))[0] == 67:
        py.press('z')
    time.sleep(1)
© www.soinside.com 2019 - 2024. All rights reserved.