admin管理员组

文章数量:1405170

I need to pause the program until the user presses a key, and then it should return whatever key was pressed.

Most places I look show one of two solutions:

# This doesn't work with what I need for obvious reasons
return input("Enter key here >>> ")

# but sometimes they'll use something like this:
import keyboard
while True:
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN:
        return event.name

But the second example, while it does only return the key when it's first pressed down as expected, there's an issue with this approach, in that if I put a regular input after using this bit of code (key = input("Enter key here >>> ")), the key that's pressed gets typed in to the input.

How would I only return the key when it's first pressed down (not held), and also use up that key press (not have the key press do anything else)?

I need to pause the program until the user presses a key, and then it should return whatever key was pressed.

Most places I look show one of two solutions:

# This doesn't work with what I need for obvious reasons
return input("Enter key here >>> ")

# but sometimes they'll use something like this:
import keyboard
while True:
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN:
        return event.name

But the second example, while it does only return the key when it's first pressed down as expected, there's an issue with this approach, in that if I put a regular input after using this bit of code (key = input("Enter key here >>> ")), the key that's pressed gets typed in to the input.

How would I only return the key when it's first pressed down (not held), and also use up that key press (not have the key press do anything else)?

Share asked Mar 8 at 23:42 TheMystZTheMystZ 921 silver badge8 bronze badges 1
  • 1 there is also module getch which can also get char without displaying it. It imitates function which is popular in C. – furas Commented Mar 9 at 6:26
Add a comment  | 

1 Answer 1

Reset to default 3

If you use suppress=True, the key press is not passed on to the system, so it won’t be stored in the input buffer. This prevents the key from appearing in any following input() calls.

import keyboard
while True:
    event = keyboard.read_event(suppress=True)
    if event.event_type == keyboard.KEY_DOWN:
        return event.name

本文标签: keyboardHow would I wait for a SINGLE key press in pythonStack Overflow