Home > Back-end >  Simple keyboard program with issues
Simple keyboard program with issues

Time:02-02

This program sometimes counts one key press as 2 presses or as 0,5 press. Program:

import keyboard
while True:
    if keyboard.read_key() == 'h':
        print("1")
    elif keyboard.read_key() == 'j':
        print("2")   
    elif keyboard.read_key() == 'k':
       print("3")

I want this program to count 1 key press as one action. I have no clue how to solve this issue.

CodePudding user response:

The keys (events register) are double because you press the "h" key and release the "h" key. The answer is here: keyboard.read_key() records 2 events

try this:

import keyboard
while True:
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN and event.name == 'h':
        print('1')
    elif event.event_type == keyboard.KEY_DOWN and event.name == 'j':
        print('2')
    elif event.event_type == keyboard.KEY_DOWN and event.name == 'k':
        print('3')
  • Related