按下键盘按钮时停止我的代码

Stop my code when pressing keyboard button

我的问题是当我按下“p”时代码没有停止。我必须发送垃圾邮件“p”来停止代码,可能有 time.sleep,我必须等待它,但我等不及了。我想在按下 p 时立即停止代码。有什么办法吗?有我的代码

import pyautogui as pg
import keyboard
import time
from PIL import Image

button = "p"

def m():
    if pg.locateOnScreen('Screenshot_2.png', confidence = 0.9):
        pc = pg.locateOnScreen('Screenshot_2.png', confidence = 0.9)
        pg.center(pc)
        pg.click(pc)
        print('found!')
        time.sleep(2)
    else:
        time.sleep(3)
        print('not found!')
        
        
while True:
    m()
    if keyboard.is_pressed(button):
        print("stopped")
        break

因为它正在检查是否在执行 if 语句的确切时刻按下了键。当该循环旋转得如此之快时,这是一个问题。您可以使用回调来缓存应该停止的条件。

import pyautogui as pg
import keyboard
import time
from PIL import Image

button = "p"

stop = False
def onkeypress(event):
    global stop
    if event.name == button:
        stop = True

def m():
    if pg.locateOnScreen('Screenshot_2.png', confidence = 0.9):
        pc = pg.locateOnScreen('Screenshot_2.png', confidence = 0.9)
        pg.center(pc)
        pg.click(pc)
        print('found!')
        time.sleep(2)
    else:
        time.sleep(3)
        print('not found!')
        
      
keyboard.on_press(onkeypress)  
while True:
    m()
    if stop:
        print("stopped")
        break