Increase just by one when a key is pressed

三世轮回 提交于 2021-01-28 02:25:03

问题


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

回答1:


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



回答2:


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.




回答3:


I haven't used that module, but you probably want the same thing that you would want in javascript. keyboard.KEY_DOWN instead of is_pressed.

https://github.com/boppreh/keyboard#keyboard.KEY_DOWN

You probably need to handle things asynchronously as well.




回答4:


import keyboard 
import time 
shot_pressed = 0 
try: 
    while True:
        if keyboard.is_pressed("S"):
            shot_pressed += 1
            time.sleep(0.1)
            print(sh)
except Exception as er:
    pass

Or can use read key

try:
    shot_pressed = 0 
    while True:
        key.read_key()
        if key.is_pressed("s"):
            sh += 1
            print(shot_pressed)
except Exception as er:
    pass


来源:https://stackoverflow.com/questions/47184374/increase-just-by-one-when-a-key-is-pressed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!