检测在python中按下的键不起作用

时间:2018-07-02 16:20:09

标签: python keyboard key python-multithreading msvcrt

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")

试图创建一个循环,当我按下“ x”时退出,并在按下“ z”时键入/停止从名为“名称”的数组中键入名称,但是,我同时按下了“ x”和“ z”但是他们什么都没有,有帮助吗?

1 个答案:

答案 0 :(得分:0)

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()

我没有使用全局变量,而是使用了存储状态的“静态”类。我还使用了另一个模块来监听按键输入。

我想这就是你想要的。

编辑:您不必将主循环作为线程。如果您想做其他事情,则将其设置为线程(取消注释两行并注释最后一行),或仅保留其原样。