Skip to main content
 首页 » 编程设计

python之如何通过单击特定的键盘键来打破 pyautogui 中的 while 循环

2024年11月24日27sxdcgaq8080

我想通过单击特定键来破坏我的代码,因为它不可能用鼠标来完成(程序正在使用鼠标)。

import pyautogui 
import time 
from mss import mss 
 
start_x = 610 
start_y = 600 
 
cords_x = [0, 140, 280, 420] 
 
bbox = (start_x, start_y, start_x + 500, start_y + 1) 
 
 
def start(): 
    with mss() as sct: 
        while True: 
            img = sct.grab(bbox) 
            for cord in cords_x: 
                if img.pixel(cord, 0)[0] < 80: 
                    pyautogui.click(start_x + cord, start_y) 
 
 
 
time.sleep(5) 
start() 

请您参考如下方法:

你只需要下载键盘模块并像这样导入

import pyautogui 
import time 
from mss import mss 
import keyboard 
 
def start(): 
    with mss() as sct: 
        while True: 
            img = sct.grab(bbox) 
            for cord in cords_x: 
                if img.pixel(cord, 0)[0] < 80: 
                    pyautogui.click(start_x + cord, start_y) 
 
            try: 
                if keyboard.is_pressed('q'): # it will stop working by clicking q you can change to to any key 
                    break 
                else: 
                    pass 
            finally: 
                pass 
 
 
time.sleep(5) 
start()