当用户单击开始键时,代码将从键盘获取输入,并在用户单击退出键时终止自动点击器,自动点击器开始单击指针放置在屏幕上的任何位置。我们将在这里使用pynput模块。
自动点击器是一个脚本,您可以根据需要多次自动控制鼠标和键盘。它使用用户定义的键进行控制。它适用于 Windows、Mac 和 Linux 等各种平台。pywin32 模块中存在自动点击器。
在这个项目中,我们将使用跨平台模块pynput来同时控制鼠标和监视键盘,以创建简单的自动点击器。为了检查鼠标事件,我们将为此执行安装pynput 模块(用于控制鼠标),在 cmd 中安装模块:
pip install pynput 。
验证pynput模块是否已成功安装到您的工作环境中:在cmd或Python Shell系统上打开 IDLE 。执行命令:
import pynput
执行此命令后,输出应该给出零错误,这意味着模块已成功安装。
现在让我们继续使用 Python 构建自动点击器所需的代码。
下面是完整的程序:
# importing time and threading
import time
import threading
from pynput.mouse import Button, Controller
# pynput.keyboard is used to watch events of
# keyboard for start and stop of auto-clicker
from pynput.keyboard import Listener, KeyCode
# four variables are created to
# control the auto-clicker
delay = 0.001
button = Button.right
start_stop_key = KeyCode(char='a')
stop_key = KeyCode(char='b')
# threading.Thread is used
# to control clicks
class ClickMouse(threading.Thread):
# delay and button is passed in class
# to check execution of auto-clicker
def __init__(self, delay, button):
super(ClickMouse, self).__init__()
self.delay = delay
self.button = button
self.running = False
self.program_running = True
def start_clicking(self):
self.running = True
def stop_clicking(self):
self.running = False
def exit(self):
self.stop_clicking()
self.program_running = False
# method to check and run loop until
# it is true another loop will check
# if it is set to true or not,
# for mouse click it set to button
# and delay.
def run(self):
while self.program_running:
while self.running:
mouse.click(self.button)
time.sleep(self.delay)
time.sleep(0.1)
# instance of mouse controller is created
mouse = Controller()
click_thread = ClickMouse(delay, button)
click_thread.start()
# on_press method takes
# key as argument
def on_press(key):
# start_stop_key will stop clicking
# if running flag is set to true
if key == start_stop_key:
if click_thread.running:
click_thread.stop_clicking()
else:
click_thread.start_clicking()
# here exit method is called and when
# key is pressed it terminates auto clicker
elif key == stop_key:
click_thread.exit()
listener.stop()
with Listener(on_press=on_press) as listener:
listener.join()
现在让我们执行我们编写的 python 程序,然后按开始 (a)和停止 (a)键以启动自动点击器。