【问题标题】:Restrict/block key presses for input in Python and prevent keyboard key press appearing on next prompt在 Python 中限制/阻止按键输入并防止键盘按键出现在下一个提示符上
【发布时间】:2020-11-09 03:01:01
【问题描述】:

我正在寻找一种在输入期间限制/阻止按键的方法,但允许某些键除外。另外,我不希望在屏幕上注册受限制/阻止的按键。

基本示例:

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

【问题讨论】:

    标签: python windows keyboard keyboard-events


    【解决方案1】:

    使用keyboard.block_key(key)

    来自doc

    keyboard.block_key(key)
    抑制给定键的所有键事件,无论修饰符如何。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-23
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 2014-08-23
      相关资源
      最近更新 更多