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
1 Answer
Reset to default 3If 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
版权声明:本文标题:keyboard - How would I wait for a SINGLE key press in python - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744882741a2630304.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论