如何使用 Python 暂时禁用键盘输入 [英] How to temporarily disable keyboard input using Python

查看:91
本文介绍了如何使用 Python 暂时禁用键盘输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 为 Windows 编写一个简单的程序,该程序利用了 time 模块.具体来说,我使用 time.sleep(x) 暂停程序一小段时间,通常为 0.5-2 秒.这基本上是我在做什么:

I'm writing a simple program for Windows using Python, and this program takes advantage of the time module. Specifically, I'm using time.sleep(x) to pause the program for a short moment, generally 0.5-2 seconds. Here's basically what I'm doing:

import time
time.sleep(2)

while True:
    x = input(prompt)
    if x == 'spam':
        break

问题在于,如果用户在 time.sleep 暂停时按下 Enter,那么这些输入将计入 while 循环中的输入.这导致 prompt 被打印多次,令人沮丧.

The problem with this is, if the user presses enter while time.sleep has it paused, then those enters will be counted towards the input in the while loop. This results in prompt being printed several times, which is frustrating.

我想知道是否有办法在 time.sleep 进行时暂时禁用键盘输入,然后再启用它.像这样:

I want to know if there's a way to temporarily disable keyboard input while time.sleep is going on, and then enable it afterwards. Something like this:

import time
disable_keyboard_input()
time.sleep(2)
enable_keyboard_input()

while True:
    etc.

有谁知道使用 Python 做到这一点的方法吗?提前致谢!

Does anyone know of a way to do this using Python? Thank you in advance!

推荐答案

我发现这非常有效:

import time
class keyboardDisable():

    def start(self):
        self.on = True

    def stop(self):
        self.on = False

    def __call__(self): 
        while self.on:
            msvcrt.getwch()


    def __init__(self):
        self.on = False
        import msvcrt

disable = keyboardDisable()
disable.start()
time.sleep(10)
disable.stop()

它阻止用户输入任何内容;当您按下键盘上的某个键时,什么也没有发生.

It stops the user from typing anything; when you press a key on the keyboard, nothing happens.

这篇关于如何使用 Python 暂时禁用键盘输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆