why is this code not working with library keyboard

Question:

If I press ctrl and alt at the same time, my program does nothing. I want if I press ctrl and alt at the same time python will automatically refresh the page 100 times.
Does anyone know why this isn’t working and what I need to change?

from pynput import keyboard


def on_press(key):
   if key == keyboard.Key.esc:
        return False  # stop listener
   try:
        k = key.char  # single-char keys
   except Exception as ex:
        k = key.name  # other keys
   if k in ['ctl'+'alt']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)


listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys
Asked By: Robbe Vermandel

||

Answers:

I have been testing your example and it seems that the library distinguishes between left and right ‘Ctrl’ and ‘Alt’.

Here when I pressed 'Ctrl left'

You should also note that only ONE KEY is detected, so the expression ‘if k in ['ctl'+'alt']:‘ will never be TRUE.

If you change it to ‘if k in ['ctrl_l', 'alt_l']:‘ (note that I changed the names of the keys as I said before that every key is different) at least one of them will be recognised. The approach given to achieve your goal is not the right one. Check this approach or something like this:

from pynput import keyboard

# The key combination to check
COMBINATION = {keyboard.Key.ctrl_l, keyboard.Key.alt_l}

# The currently active modifiers
current = set()


def on_press(key):
    if key in COMBINATION:
        current.add(key)
        if all(k in current for k in COMBINATION):
            print('PRESSED')
    if key == keyboard.Key.esc:
        listener.stop()


def on_release(key):
    try:
        current.remove(key)
    except KeyError:
        pass


with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
Answered By: Beer Baron
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.