type(list[0]) returns pynput.keyboard._win32.KeyCode

假装没事ソ 提交于 2021-02-05 11:57:17

问题


My problem is how pynput returns the data (I hope that's how you would say it?).

So what I'm trying to do is have the listener record keyboard input, then use what letters are added to the list to make a string in word. Although, it seems like the letters aren't strings. Instead they return as pynput.keyboard._win32.KeyCode

Is there a way to convert that to a python readable string or something?
Like if: i typed f, t, w

print(type(list[0]), word)
return 'f', ftw

what it comes out as so far is

f[] pressed
t['f'] pressed
w['f', 't'] pressed
 ['f', 't', 'w'] pressed
['f', 't', 'w'] <class 'pynput.keyboard._win32.KeyCode'> # then basically nothing for word  
[] pressed

from pynput import keyboard


list = []
word = ''.join(list)


def press(key): 
    print(list, 'pressed') 
    if key is not keyboard.Key.space:
        list.append(key)
    elif keyboard.Key.space is key:
        pass
    elif keyboard.Key.enter is key:
        pass


def release(key):
    if key == keyboard.Key.space:
        print(type(list[0]), word)
        if word in hkey:
            func()
        list.clear()

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

回答1:


You can extract the character from the pressed key by using the char attribute of the pynput.keyboard._win32.KeyCode. In other words, in your press function, you would append key.char to the list. Also, I would avoid using list as a variable name.

def press(key):
    print(_list, 'pressed')
    if key is not keyboard.Key.space:
        _list.append(key.char)         # <-- Note: key.char
    elif keyboard.Key.space is key:
        pass
elif keyboard.Key.enter is key:
    pass


来源:https://stackoverflow.com/questions/52241868/typelist0-returns-pynput-keyboard-win32-keycode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!