0

我目前被困在一个使用 CV2 用 Python 编写的程序上。该程序使用由热键触发的 while 循环。我想使用热键打开和关闭程序/循环。我遇到的问题是,由于热键功能在 while 循环之外,因此在循环运行时不再识别它(至少我认为这是问题所在),因此我不能再关闭循环。

这是我目前正在使用的代码:

import PIL.ImageGrab
import cv2
import numpy as np
import time
import pyautogui
from pynput import keyboard
from pynput.keyboard import Key

COMBINATIONS = [
    {keyboard.Key.shift, keyboard.KeyCode(char="a")},
    {keyboard.Key.shift, keyboard.KeyCode(char="A")}
    ]
isRunning = False

current = set()

def test():
    print("This is a seccessful test")

def templateMatch():

        imgGrab = PIL.ImageGrab.grab().save("background.jpg", "JPEG")
        time.sleep(2) #set interval here
        imgBGR = cv2.imread("background.jpg")
        imgGray = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2GRAY)

        template = cv2.imread("template.png", 0)
        width, height = template.shape[::-1]

        res = cv2.matchTemplate(imgGray, template, cv2.TM_CCOEFF_NORMED)
        threshold = 0.99
        loc = np.where(res >= threshold)

        for pt in zip(*loc[::-1]):
            print(pt)

        pyautogui.click(pt[0]+width/2, pt[1]+height/2)

def on_press(key):
              if any([key in COMBO for COMBO in COMBINATIONS]):
                     current.add(key)
                     if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
                         global isRunning
                         isRunning = not isRunning
                         print(isRunning)
                         while(isRunning):
                             templateMatch()                            

def on_release(key):
           if any([key in COMBO for COMBO in COMBINATIONS]):
               current.remove(key)

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
           listener.join()
4

0 回答 0