Python键盘库箭头键问题

时间:2019-03-03 20:55:48

标签: python keyboard

我正在编写一个脚本,该脚本需要截屏并解码图像名称中的特定按键,如下所示。 我的问题是,当我按左键盘箭头时,也按了数字4。 我在Google或键盘库的文档中找不到任何内容, 任何建议都很好。 我正在使用Windows和Python 3.6.5

(75,)
left arrow pressed
(5, 75)
4 pressed

向下箭头也会发生同样的事情,但数字3会发生

(80,)
down arrow pressed
(3, 80)
2 pressed

代码

from PIL import ImageGrab
import keyboard  # using module keyboard
import time

keys = [
    "down arrow",
    "up arrow",
    "left arrow",
    "right arrow",
    "w",
    "s",
    "a",
    "d",
    "1",
    "2",
    "3",
    "4",
    "q",
    "e",
    "f"
]

if __name__ == "__main__":
    while True:
        code = []
        try:
            for key in keys:
                if keyboard.is_pressed(key):
                    print(keyboard.key_to_scan_codes(key))
                    print(f"{key} pressed")
                    code.append(1)
                else:
                    code.append(0)

            if keyboard.is_pressed('esc'):
                print(key + " pressed")
                break

            c = "".join(map(str, code))
            snapshot = ImageGrab.grab()
            save_path = str(int(time.time()*1000)) + "-" + c + ".jpg"
            snapshot.save("tmp\\" + save_path)

        except:
            break

3 个答案:

答案 0 :(得分:0)

您可能需要先停用NumLock按钮。我在NumLock处于活动状态时按Shift键时遇到一些问题。

答案 1 :(得分:0)

keyboard模块为此类实例提供了简单的解决方案,它们使用event-triggered激活,而不是您尝试时使用的polling

示例代码:

import keyboard

def handleLeftKey(e):
    if keyboard.is_pressed("4"):
        print("left arrow was pressed w/ key 4")
        # work your magic

keyboard.on_press_key("left", handleLeftKey)
# self-explanitory: when the left key is pressed down then do something

keyboard.on_release_key("left", handleLeftKey02)
# also self-explanitory: when the left key is released then do something

# don't use both ...on_release & ...on_press or it will be
# triggered twice per key-use (1 up, 1 down)

替换下面的代码并进行更改以适合您的需求。

if __name__ == "__main__":
    while True:
        code = []
        try:
            for key in keys:
                if keyboard.is_pressed(key):
                    print(keyboard.key_to_scan_codes(key))
                    print(f"{key} pressed")
                    code.append(1)
                else:
                    code.append(0)

另一种更具动态性的方法如下:

import keyboard

keys = [
    "down",
    "up",
    "left",
    "right",
    "w",
    "s",
    "a",
    "d",
    "1",
    "2",
    "3",
    "4",
    "q",
    "e",
    "f"
]

def kbdCallback(e):
    found = False
    for key in keys:
        if key == keyboard.normalize_name(e.name):
            print(f"{key} was pressed")
            found = True
            # work your magic

    if found == True:
        if e.name == "left":
            if keyboard.is_pressed("4"):
                print("4 & left arrow were pressed together!")
                # work your magic

keyboard.on_press(kbdCallback)
# same as keyboard.on_press_key, but it does this for EVERY key

我注意到的另一个问题是,您在使用"left arrow"时确实将其识别为"left"(至少在我的系统上,它可能与您的系统有所不同,但是我认为您希望它能正常工作)在所有系统上都可以使用"left"来更安全)

您可以使用的最后一个方法是非常静态的类型,没有动态功能,但是在"4+left""left+4"的情况下可以使用

import keyboard

def left4trigger:
    print("the keys were pressed")

keyboard.add_hotkey("4+left", left4trigger)
# works as 4+left or left+4 (all of the examples do)

您似乎很聪明,可以从那里找出其余的内容。

答案 2 :(得分:0)

当心,语言可能会起作用!就我而言,“向上”箭头已翻译为我的本地语言,您可以运行以下代码来获取计算机的键值:

import keyboard    
def onkeypress(event):
    print(event.name)

keyboard.on_press(onkeypress)

#Use ctrl+c to stop
while True:
    pass