简体   繁体   中英

Detect if key was pressed once

I wanted to do an action, as soon as my f key is pressed. The problem is that it spams the action.

import win32api

while True:
    f_keystate = win32api.GetAsyncKeyState(0x46)

    if f_keystate < 0:
        print("Pressed!")

I would like this without "Pressed." being spammed but only printed once.

You need a state variable that will keep track of whether the key has been pressed after it's been released.

f_pressed = False

while not f_pressed:
    f_pressed = win32api.GetAsyncKeyState(0x46) < 0

print("Pressed!")

Because in the while loop, when the f key is pressed, GetAsyncKeyState will detect that the f key is always in the pressed state. As a result, the print statement is called repeatedly.

Try the following code, you will get the result you want:

import win32api

while True:
    keystate = win32api.GetAsyncKeyState(0x46)&0x0001
    if keystate > 0:
       print('F pressed!')

I'm super late, but I ran across the same problem myself when using the keyboard module. Here's the solution I found, and yes, it is asynchronous.

    if keyboard.is_pressed('f'):
        if checksPressed == 0:
            # run code
        checksPressed += 1
    else:
        checksPressed = 0

or for win32api

if win32api.GetAsyncKeyState(0x46) < 0:
        if checksPressed == 0:
            # run code
        checksPressed += 1
    else:
        checksPressed = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM