简体   繁体   中英

How to detect keypress in python using keyboard module?

I am making a program in python to detect what key is pressed and based on my keyboard it will make a decision.

I want to implement it using keyboard module in python.

I would do something like this,

import keyboard
while True:
    if keyboard.read_key() == 'enter':
        print('Enter is pressed)
    if keyboard.read_key() == 'q':
        print('Quitting the program)
        break
    if keyboard.read_key() == 's':
        print('Skiping the things')

But it doesn't work. When I execute this program, I have to press s twice to execute the "s" block.

Also, I have a problem that is after the execution is finished, it writes all the keys in my command prompt is it possible to fix that?

As per Keyboard documentation :

Other applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.

One way to solve your problem with keyboard module is keyboard.wait('key')

# Blocks until you press esc
keyboard.wait('esc')

Something work around is as below:

import keyboard

keyboard.wait('enter')
print('Enter is pressed')

keyboard.wait('q')
print('Quitting the program')

keyboard.wait('s')
print('Skiping the things')

As Far I Know There is only one efficient way to Detect user input weather it keybored or mouse input Which is library called pynput......

from pynput.keyboard import Key , Listener , Controller

keyboard = Controller()

DoubleShot=False
shot=False
def on_press(key):
    global  DoubleShot
    global  shot

    if Key.num_lock == key:
        print("activate")
        DoubleShot=True
    if DoubleShot:
        if Key.shift == key:
      
            shot = not shot
            if shot:
                keyboard.press(Key.shift)
                keyboard.release(Key.shift)

def on_release(key):
    if key == Key.esc:
        return False

with Listener(on_press=on_press , on_release=on_release) as listener:
    listener.join()

i create this for a game to shoot multiple time on 'shift' clicked

  • code activate only when ' numlock ' clicked.....
  • Controller is for clicking any key you want

Note: In My case infinity looping was a problem that's why shot variable is there to stop looping

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