简体   繁体   中英

pynput key press backlog

(note: programming beginner and also stack overflow beginner, so sorry if I did something wrong)

I'm trying to write a python (python 3.7.3, if that's useful) program where when the backslash ("\\") key is held, it spams the left click button (for online games. I'll bind a mouse button to "\\", so as to not have to detect a left mouse click and run into the problem of detecting mouse clicks that the program does). My code currently works, but when "\\" is released, it takes a few seconds to stop clicking based on how long it is held.

here is my code:

from pynput.keyboard import Key, Listener
import pyautogui


def key_down(key):
    if str(key) == "'\\\\'":
        pyautogui.click()

def key_up(key):
    if str(key) == "'\\\\'":
        print('key has been lifted')

with Listener(on_press=key_down,on_release=key_up) as l:
    l.join()

Am I doing something wrong? Is there a way to fix this problem?

for anyone with the same problem in the future: idk how to solve the original problem with the backlog, but got around it with threading. here is my code now:

note: the "'\\\\\\\\'" is to check for if the backslash key is pressed, but the pynput module has it stored as "'\\\\'", so since backslash is the escape character, you need to type it "'\\\\\\\\'" to have it actually be "'\\\\'"

from pynput.keyboard import Key, Listener
import pyautogui
from threading import Thread

shouldClick = False

def click():
    while True:
        while shouldClick:
            pyautogui.click()


def key_down(key):
    global shouldClick
    if str(key) == "'\\\\'":
        shouldClick = True


def key_up(key):
    global shouldClick
    if str(key) == "'\\\\'":
        shouldClick = False
        print('key has been lifted')


def listen():
    with Listener(on_press=key_down,on_release=key_up) as l:
        l.join()


listenThread = Thread(target=listen)
clickThread = Thread(target=click)

listenThread.start()
clickThread.start()

optionally, if you want to push the limits of clicking to the extreme, you can add the following code:

thrCount = 40
print(thrCount, 'threads')
for _ in range(thrCount):
    clickThreadList.append(Thread(target=click))
for thr in clickThreadList:
    thr.start()

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