【问题标题】:PyAutoGui and PyScreezePyAutoGui 和 PyScreez
【发布时间】:2021-03-19 20:18:57
【问题描述】:

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

Traceback(最近一次调用最后一次): 文件“C:/Users/Kris/PycharmProjects/OsuBot/venv/drums.py”,第 7 行,在 如果 pyautogui.pixel(609, 440)[0] == 235: 文件“C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\pyscreez_init_.py”,第 584 行,以像素为单位 返回 (r, g, b) 退出中的文件“C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\contextlib.py”,第 120 行 下一个(self.gen) 文件“C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\pyscreez_init_.py”,第 113 行,在 __win32_openDC 引发 WindowsError(“windll.user32.ReleaseDC 失败:返回 0”) 操作系统错误:windll.user32.ReleaseDC 失败:返回 0

进程以退出代码 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】:

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

    您可以尝试使用pip install pillowpillow 库,它具有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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      • 2020-09-17
      • 2020-12-09
      • 2019-10-18
      • 2021-05-22
      • 2016-09-28
      • 2017-01-25
      相关资源
      最近更新 更多