Home > Software engineering >  Keyboard module multiple if
Keyboard module multiple if

Time:11-20

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")

Sometimes the print function only run after second key press.

Python 3.11

I literally tried every other module and every possible if-elif-while combination.

CodePudding user response:

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])

WORKS!

CodePudding user response:

import keyboard

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

This makes every print double.

CodePudding user response:

To make the code a bit cleaner, you can consider using a dictionary with messages:

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

If you have a lot of messages for different keys, using a dictionary could be faster as well.


@Sedus Just for clarity, discovered that the order of the commands had to be changed to avoid double key presses

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