gpt4 book ai didi

python - 如何检测按键?

转载 作者:IT老高 更新时间:2023-10-28 20:34:12 25 4
gpt4 key购买 nike

我正在用 Python 制作秒表类型的程序,我想知道如何检测是否按下了某个键(例如 p 表示暂停,s 表示停止),我不希望它是像 raw_input 这样的东西,它会在继续执行之前等待用户的输入。

有人知道如何在while循环中执行此操作吗?

我想做这个跨平台的,但如果这不可能,那么我的主要开发目标是 Linux。

最佳答案

Python 有一个 keyboard具有许多功能的模块。安装它,也许用这个命令:

pip3 install keyboard

然后在如下代码中使用它:

import keyboard  # using module keyboard
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
break # if user pressed a key other than the given key the loop will break

关于python - 如何检测按键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24072790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com