我正在寻找一种方法来限制/阻止输入期间按键,但允许某些按键除外。另外,我不希望在屏幕上注册受限制/阻止的按键。
基本示例:
input("Enter the letter [p] to proceed: ")
出现提示时,任何不是字母“p”的键都不会出现在屏幕上 input()
旁边。
注意:我知道使用 while
循环来检查是否按下了正确的键,但这不是我想要使用的。
作为解决方法,我使用 print()
和 Keyboard python 模块。
这是我的基本代码:
import msvcrt
import keyboard
print("Press [p] to proceed: ", end="", flush=True)
while True:
keyboard.wait("p")
while msvcrt.kbhit():
msvcrt.getch()
print("p") # print the letter "p" next to the previous print statement above
break
这可以满足我的需求,但有一个恼人的问题。然后字母“p”被刷新到控制台,出现在提示符下的下一行:
如有任何帮助,我们将不胜感激。
操作系统:Windows 10
Python版本:3.8.3
使用 Windows 终端(截至本文版本为 1.0.1811.0)
PowerShell版本:7.0.3
最佳答案
使用keyboard.block_key(key)
。
来自doc :
keyboard.block_key(key)
Suppresses all key events of the given key, regardless of modifiers.
关于python - 限制/阻止 Python 中输入的按键并防止在下一个提示中出现键盘按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62985579/