ImportError:无法从“ pynput.keyboard”导入名称“ key”

时间:2019-01-18 23:45:29

标签: python python-3.x pynput

首先,我想对这个问题是否愚蠢表示歉意。

我对此错误有疑问:

    ImportError: cannot import name 'key' from 'pynput.keyboard' 
    (C:\Users\richard\AppData\Local\Programs\Python\Python37-32\lib\site- 
    packages\pynput\keyboard\__init__.py)

您能告诉我如何解决吗?:

我尝试在Google上找到一些建议,但没有找到任何建议。也许这只是愚蠢的“问题”。

这是未完成的代码,我想尝试一下是否能正常工作,然后显示错误。

import pynput

from pynput.keyboard import key, Listener

count = 0
keys = []

def on_press(key):
    global keys, count
    print("{0} pressed".format(key))

def write_file(keys):
    with open("log.txt", "w") as f:
        for key in keys:
            f.write(key)

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

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

这是整个问题:

Traceback (most recent call last):
  File "C:/Users/richard/AppData/Local/Programs/Python/Python37- 
  32/Logger.py", line 3, in <module>
    from pynput.keyboard import key, Listener
ImportError: cannot import name 'key' from 'pynput.keyboard' 
(C:\Users\richard\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\pynput\keyboard\__init__.py)

Process finished with exit code 1

1 个答案:

答案 0 :(得分:2)

它的Key不是key

from pynput.keyboard import Key, Listener

看看文档here