'Don't know where to start when trying to make a system that can toggle my program

import time
import pyautogui
import cv2
import mss
import numpy
import pytesseract
import keyboard
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

with mss.mss() as sct:
    while True:
        mon = {'top': 321, 'left': 528, 'width': 100, 'height': 50}
        im = numpy.asarray(sct.grab(mon))
        cv2.imshow('Image', im)
        text = pytesseract.image_to_string(im)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break
        time.sleep(1)

I don't know where to start when trying to make a toggling system for this program. By toggle, I mean that when I press 'esc' the program starts running, but when I click 'esc' again, it breaks the program Please guide me through the process, as I don't know where to start.



Solution 1:[1]

Just use a toggle:

with mss.mss() as sct:
    showme = True
    while True:
        mon = {'top': 321, 'left': 528, 'width': 100, 'height': 50}
        if showme:
            time.sleep(1)
            im = numpy.asarray(sct.grab(mon))
            cv2.imshow('Image', im)
            text = pytesseract.image_to_string(im)
        key = cv2.waitKey(25)
        if key & 0xFF == ord('q'):
            break
        if key & 0xff = 0x1B:
            showme = not showme
cv2.destroyAllWindows()

Note that I moved the sleep call, so that it would respond to the wake-up "esc" hit more quickly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Roberts