简体   繁体   中英

pynput Keyboard Listener returns shift when shift is pressed, but does not modify shift_pressed

I've got a simple program to familiarize myself with Keyboard Listeners using pynput. What it does is not important. What is important is that the shift_pressed attribute never seems to change to True . My program currently looks like this:

from pynput.keyboard import Controller, Listener

boo = True
keyboard = Controller()

fib_lst = [0, 1]


def on_press(key):
    print(key)
    print(keyboard.shift_pressed)


Listener(on_press=on_press).start()

while boo:
    nxt = fib_lst[-1] + fib_lst[-2]
    input(nxt)
    fib_lst.append(nxt)

I'm trying to do something like this in on_press (or on_release ):

def on_press(key):
    if key == Key.delete:
        if keyboard.shift_pressed:
            func1()

        else:
            func2()

This code should perform func1 when shift is pressed or func2 if it is not. But it is currently only doing func2 since shift_pressed is perpetually false. What can I do differently to get shift_pressed to work as it should?

Edit 1: Specified the desired end result more clearly.

Edit 2: Changed the appending string to two different functions to add more clarity.

Edit 3: Changed the parameters of the final question to match the more recent example

I'm not hundred percent sure but when I have worked with pynput I noticed that I can handle action on key release, not key press so you can try something like below:

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.shift: # handles if key press is shift
        print('foo', end='')

def on_release(key):
    if key == keyboard.Key.shift:
        print()
    elif key == keyboard.Key.delete:
        print('bar')
    elif key == keyboard.Key.esc:
        return False

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

get_current_key_input()

if you need any other help let me know with your specific motive.

This is a bug in the pynput 1.3.5 documentation.

The various modifier state properties ( alt_pressed , alt_gr_pressed , ctrl_pressed and shift_pressed ) reflect only the state of the Controller instance; it maintains an inner modifier state which is applied when various keys are pressed---for example to uppercase characters from scripts that support it.

This state is separate from the current operating system state and will only change when you send key presses using that specific controller.

There is no general pynput method to retrieve the current global modifier state.

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