简体   繁体   中英

Detect key pressed in python not working

import pyautogui, time, threading, keyboard, msvcrt

global active, exitp
active = False
exitp = False

Names = []

def mainLoop():
    global active, exitp
    pressedkey = msvcrt.getch()
    while True:
         if pressedkey == 'z':
            active = not active
         elif pressedkey == 'x':
            exitp = False
            break

def running():
    global exitp
    while not exitp:
        print("Running")
        time.sleep(3)

start = time.time()
print("Your screen size is: " + str(pyautogui.size()))
width, height = pyautogui.size()
t1 = threading.Thread(target=mainLoop, args=())
t2 = threading.Thread(target=running, args=())
t1.start()
t2.start()
while not exitp:
    if active:
        pyautogui.click(90, height - 110)
        for i in range(len(Names)):
            if active:
                pyautogui.typewrite(Names)
                pyautogui.press("enter")
            else:
                break
        active = False
end = time.time()
print("Execution time: " + str(end-start) + " seconds")

trying to make a loop that exits when i press 'x', and types/stops typing names from my array called "Names" when pressing 'z', however, i'm pressing both 'x' and 'z' but they don't anything, help?

from pynput import keyboard

import pyautogui
import threading
import sys

class Status:
    _exit = False
    active = True

names = [str(i) for i in range(0, 10, 1)]

width, height = pyautogui.size()

def mainThread():
    listenerThread = keyboard.Listener(on_press = onKeyPress)
    listenerThread.start()

    while(not Status._exit):
        if (not Status.active):
            continue

        pyautogui.click(90, height - 110)

        for i in range(len(names)):
            if (not Status.active or Status._exit):
                break

            pyautogui.typewrite(names[i])
            pyautogui.press("enter")


    keyboard.Listener.stop(listenerThread)
    print("Stopped listerning")
    sys.exit(0)


def onKeyPress(key):
    print("Still listerning")

    try:
        k = key.char
    except Exception:
        k = key.name

    if (k == "z"):
        Status.active = not Status.active

    elif (k == "x"):
        Status._exit = not Status._exit


#controlThread = threading.Thread(target = mainThread)
#controlThread.start()

mainThread()

Instead of using globals I used a 'static' class which stored the status. I also used a different module to listen to key inputs.

I think this is what you wanted.

EDIT: You don't have to have the main loop as a thread. If you wanted to do other things then set it as a thread (uncomment the two lines and comment the last line) or just leave it how it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM