1

我的问题是如何pynput返回数据(我希望你会这么说?)。

所以我想做的是让听众记录键盘输入,然后使用添加到列表中的字母来制作单词字符串。虽然,看起来这些字母不是字符串。相反,他们返回为pynput.keyboard._win32.KeyCode

有没有办法将其转换为 python 可读字符串或其他东西?
比如:我输入了f, t, w

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

到目前为止的结果是

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()
4

1 回答 1

2

char您可以使用 的属性从按下的键中提取字符pynput.keyboard._win32.KeyCode。换句话说,在您的press函数中,您将追加key.char到列表中。另外,我会避免list用作变量名。

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
于 2018-09-09T07:05:13.547 回答