最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

keyboard - How would I wait for a SINGLE key press in python - Stack Overflow

programmeradmin5浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论