我最近开始使用 python,并且对这个主题相当陌生。目前,我正在开发一个项目,该项目将根据屏幕上的特定像素值模拟键盘按下。基本上,如果“这样的像素”被着色为“这样的颜色”,然后单击/按下。但是,我的代码有一个错误。有时,它运行得很好,但随后随机停止运行。其他时候,它根本不运行。在这两种情况下,都会出现错误(如下代码)。这是我当前的代码:
import random
import time
import keyboard
import pyautogui
import win32api
import win32con
from pyautogui import *
from pynput.keyboard import Key, Controller
simulate = Controller()
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)
def jump():
simulate.press(Key.up)
simulate.release(Key.up)
click(650, 540)
print("Jumped!")
def duck():
simulate.press(Key.down)
simulate.release(Key.down)
print("Ducked!")
def restart():
click(950, 500)
def switch():
simulate.press(Key.alt)
simulate.press(Key.tab)
simulate.release(Key.alt)
simulate.release(Key.tab)
def play():
while not keyboard.is_pressed('a'):
if pyautogui.pixel(660, 540)[0] != 247:
jump()
if pyautogui.pixel(950, 500)[0] == 83:
restart()
switch()
play()
switch()
这是控制台:
Traceback (most recent call last):
File "C:...\main.py", line 59, in <module>
play()
File "C:...\main.py", line 51, in play
if pyautogui.pixel(660, 540)[0] != 247:
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line 584, in pixel
return (r, g, b)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\contextlib.py", line 124, in __exit__
next(self.gen)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\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
为什么这段代码有时只工作,然后随机停止?是下载或导入的问题,还是其他问题?如果您能提供帮助,将不胜感激。谢谢!