python 键盘模块多重if

6pp0gazn  于 2022-11-21  发布在  Python
关注(0)|答案(3)|浏览(189)
import keyboard

while True:
    if keyboard.read_key() == "up":
        print("up")
    if keyboard.read_key() == "down":
        print("down")
    if keyboard.read_key() == "enter":
        print("enter")

有时打印功能只在按下第二个键后运行。
Python 3.11语言
我几乎尝试了所有其他模块和所有可能的if-elif-while组合。

cs7cruho

cs7cruho1#

import keyboard

message = {"up": "up", "down": "down", "enter": "enter"}

while True:
    key = keyboard.read_key()
    if key in message:
        while keyboard.is_pressed(key):
            pass
        print(message[key])

有效!

iyr7buue

iyr7buue2#

import keyboard

while True:
    keypressed = keyboard.read_key()
    if keypressed == "up":
        print("up")
    if keypressed == "down":
        print("down")
    if keypressed == "enter":
        print("enter")

这会使每个打印加倍。

hsgswve4

hsgswve43#

为了使代码更简洁,可以考虑使用带有消息的dictionary

import keyboard
message  =  {"up": "up", "down": "down", "enter": "enter"}
while True:
    key = keyboard.read_key()
    
    if key in message:
        print(message[key])
        while keyboard.is_pressed(key): pass

如果你有很多不同键的消息,使用dictionary也会更快。
@Sedus为了清楚起见,发现必须更改命令的顺序以避免双击

while keyboard.is_pressed(key): pass
        print(message[key])

相关问题