如何在Python中禁用和启用Windows的键盘输入?
你好,我现在正在为《Valorant》制作一个触发机器人(我并不是想作弊,只是想学习Python编程,并把它和像素检测和输入操作结合起来),我想问一下怎么禁用键盘输入,然后在完成其他任务后再启用它。大概是这样的:
Import mouse
Import keyboard
//diable keyboard here
Mouse.click(„left“)
//enable keyboard here
这只是程序的一部分,如果需要其他部分我当然可以补充。
我试着找一些相关的信息,但对我来说都没用。希望能得到帮助。抱歉我的英语可能不好。
3 个回答
0
使用 keyboard
模块,我们可以阻止键盘上的每一个按键:
import keyboard
for key in range(150): #150 should be enough for all the keys on the keyboard
keyboard.block_key(key) #block the key until unblocked
#do stuff
for key in range(150):
keyboard.unblock_key(key) #unblocks all the keys
为了让这个在你的程序中更简单、更易读,你可以为此创建两个简单的函数:
import keyboard
def block():
for key in range(150):
keyboard.block_key(key)
def unblock():
for key in range(150):
keyboard.unblock_key(key)
block()
#do stuff
unblock()
0
你可以使用Python自带的模块来屏蔽键盘输入。
通常,当你屏蔽键盘输入的时候,也希望能屏蔽一些信号。因此,这个工具类默认也提供了这个功能。
from termios import tcgetattr, tcsetattr, TCSAFLUSH
from sys import stdin
from tty import setraw
import signal
class Blocker:
def __init__(self, ignore_signals=True):
self._ignore_signals = ignore_signals
@staticmethod
def siglist():
signames = [
"SIGABRT",
"SIGINT",
"SIGTERM",
"SIGBREAK",
"SIGALRM",
"SIGCONT",
"SIGHUP",
"SIGUSR1",
"SIGUSR2",
"SIGWINCH",
]
_siglist = []
for signame in signames:
if (sig := getattr(signal, signame, None)) is not None:
_siglist.append(sig)
return _siglist
def __enter__(self):
self._fd = stdin.fileno()
self._attr = tcgetattr(self._fd)
setraw(self._fd)
if self._ignore_signals:
self._sigfuncs = {
s: signal.signal(s, signal.SIG_IGN) for s in Blocker.siglist()
}
else:
self._sigfuncs = None
return self
def __exit__(self, *_):
if self._sigfuncs is not None:
for kv in self._sigfuncs.items():
signal.signal(*kv)
if self._attr is not None:
tcsetattr(self._fd, TCSAFLUSH, self._attr)
import time
# during sleep, keyboard input and observable signals will be ignored
with Blocker():
time.sleep(5)
0
你可以使用pyautogui这个库来暂时阻止键盘输入。完成你想做的事情后,再把它重新启用。
import pyautogui
# Disable keyboard input
pyautogui.FAILSAFE = False
# Perform your task
pyautogui.click('left')
# Enable keyboard input
pyautogui.FAILSAFE = True