python - 返回按下的键的名称

时间:2017-05-22 08:11:50

标签: python

我想在python(windows)中获取按下键的名称

我遇到过这段代码:

import msvcrt
return msvcrt.getch()

但它仅返回数字和字母的键名,并且不返回Shift,VolumeUp,播放/暂停,F12或PrtScreen等键的名称。

是否有能够返回键盘上所有键名称的函数或代码?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

win32con模块确实包含所有虚拟键的映射,并且可以直接提取这些虚拟键并创建自己的查找字典,如下所示:

import win32con

keys = {getattr(win32con, v) : v for v in dir(win32con) if v.startswith("VK_")}

def get_key_text(key):
    return keys.get(key, chr(key))

print get_key_text(13)      # return key
print get_key_text(32)      # space key
print get_key_text(175)     # volume up
print get_key_text(65)      # a

所以这会显示以下内容:

VK_RETURN
VK_SPACE
VK_VOLUME_UP
A

创建的keys字典如下所示:

{1: 'VK_LBUTTON', 2: 'VK_RBUTTON', 3: 'VK_CANCEL', 4: 'VK_MBUTTON', 5: 'VK_XBUTTON1', 6: 'VK_XBUTTON2', 8: 'VK_BACK', 9: 'VK_TAB', 12: 'VK_CLEAR', 13: 'VK_RETURN', 16: 'VK_SHIFT', 17: 'VK_CONTROL', 18: 'VK_MENU', 19: 'VK_PAUSE', 20: 'VK_CAPITAL', 21: 'VK_KANA', 23: 'VK_JUNJA', 24: 'VK_FINAL', 25: 'VK_KANJI', 27: 'VK_ESCAPE', 28: 'VK_CONVERT', 29: 'VK_NONCONVERT', 30: 'VK_ACCEPT', 31: 'VK_MODECHANGE', 32: 'VK_SPACE', 33: 'VK_PRIOR', 34: 'VK_NEXT', 35: 'VK_END', 36: 'VK_HOME', 37: 'VK_LEFT', 38: 'VK_UP', 39: 'VK_RIGHT', 40: 'VK_DOWN', 41: 'VK_SELECT', 42: 'VK_PRINT', 43: 'VK_EXECUTE', 44: 'VK_SNAPSHOT', 45: 'VK_INSERT', 46: 'VK_DELETE', 47: 'VK_HELP', 91: 'VK_LWIN', 92: 'VK_RWIN', 93: 'VK_APPS', 96: 'VK_NUMPAD0', 97: 'VK_NUMPAD1', 98: 'VK_NUMPAD2', 99: 'VK_NUMPAD3', 100: 'VK_NUMPAD4', 101: 'VK_NUMPAD5', 102: 'VK_NUMPAD6', 103: 'VK_NUMPAD7', 104: 'VK_NUMPAD8', 105: 'VK_NUMPAD9', 106: 'VK_MULTIPLY', 107: 'VK_ADD', 108: 'VK_SEPARATOR', 109: 'VK_SUBTRACT', 110: 'VK_DECIMAL', 111: 'VK_DIVIDE', 112: 'VK_F1', 113: 'VK_F2', 114: 'VK_F3', 115: 'VK_F4', 116: 'VK_F5', 117: 'VK_F6', 118: 'VK_F7', 119: 'VK_F8', 120: 'VK_F9', 121: 'VK_F10', 122: 'VK_F11', 123: 'VK_F12', 124: 'VK_F13', 125: 'VK_F14', 126: 'VK_F15', 127: 'VK_F16', 128: 'VK_F17', 129: 'VK_F18', 130: 'VK_F19', 131: 'VK_F20', 132: 'VK_F21', 133: 'VK_F22', 134: 'VK_F23', 135: 'VK_F24', 144: 'VK_NUMLOCK', 145: 'VK_SCROLL', 160: 'VK_LSHIFT', 161: 'VK_RSHIFT', 162: 'VK_LCONTROL', 163: 'VK_RCONTROL', 164: 'VK_LMENU', 165: 'VK_RMENU', 166: 'VK_BROWSER_BACK', 167: 'VK_BROWSER_FORWARD', 173: 'VK_VOLUME_MUTE', 174: 'VK_VOLUME_DOWN', 175: 'VK_VOLUME_UP', 176: 'VK_MEDIA_NEXT_TRACK', 177: 'VK_MEDIA_PREV_TRACK', 179: 'VK_MEDIA_PLAY_PAUSE', 229: 'VK_PROCESSKEY', 246: 'VK_ATTN', 247: 'VK_CRSEL', 248: 'VK_EXSEL', 249: 'VK_EREOF', 250: 'VK_PLAY', 251: 'VK_ZOOM', 252: 'VK_NONAME', 253: 'VK_PA1', 254: 'VK_OEM_CLEAR'}