Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase just by one when a key is pressed

I want to increase the variable "shot_pressed" just by one when the key "s" is pressed no matter how long I pressed. But the result is that the variable keeps on increasing. The longer I pressed, the bigger the value of the variable. Below is a part of my code.

import keyboard

shot_pressed = 0

if keyboard.is_pressed('s'):
    shot_pressed += 1
like image 873
user8654396 Avatar asked Dec 13 '25 07:12

user8654396


2 Answers

First of all looks like you use https://pypi.python.org/pypi/keyboard

Second, I assume your code is not like you wrote above but like

import keyboard

shot_pressed = 0

while True:
    if keyboard.is_pressed('s'):
        shot_pressed += 1
        print("shot_pressed %d times"%shot_pressed)

If yes, here is the core of the problem: is_pressed will be always True, while key is pressed. So if condition will be True and while will repeat it many times.

There are two ways of dealing with that.

1) Use the same method, but check if this is the first is_pressed moment, so inroduce was_pressed variable:

import keyboard

shot_pressed = 0
was_pressed = False

while True:
    if keyboard.is_pressed('s'):
        if not was_pressed:
            shot_pressed += 1
            print("shot_pressed %d times"%shot_pressed)
            was_pressed = True
    else:
        was_pressed = False

2) Better use the library. You can set a hook, so on key pressed your function will be called (only once for one press). So the code will look like this:

import keyboard

shot_pressed = 0

def on_press_reaction(event):
    global shot_pressed
    if event.name == 's':
        shot_pressed += 1
        print("shot_pressed %d times"%shot_pressed)

keyboard.on_press(on_press_reaction)

while True:
    pass
like image 62
Leonid Mednikov Avatar answered Dec 14 '25 21:12

Leonid Mednikov


I do not know that keyboard module but the problem with your code is that the program takes input once. Your program should wait next input from keyboard. Try to use while loop to take inputs from user.

like image 40
Ersel Er Avatar answered Dec 14 '25 19:12

Ersel Er