Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to break the while loop in pyautogui by clicking on specific keyboard key

i want to break my code by clicking specific key because its impossible to do it with mouse (mouse is being used by program).

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()
like image 747
Elmo Avatar asked Nov 01 '25 05:11

Elmo


1 Answers

you just need to download keyboard module and import it like this

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()
like image 139
Saba Avatar answered Nov 03 '25 21:11

Saba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!