Detect if key was pressed once

后端 未结 2 1859
有刺的猬
有刺的猬 2021-01-28 21:49

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 = win32         


        
相关标签:
2条回答
  • 2021-01-28 22:08

    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!")
    
    0 讨论(0)
  • 2021-01-28 22:20

    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!')
    
    0 讨论(0)
提交回复
热议问题