所以当我在互联网上遇到此自动点击程序代码时,我就迷上了python
import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode
delay = 0.001
button = Button.left
start_stop_key = KeyCode(char='s')
exit_key = KeyCode(char='e')
class ClickMouse(threading.Thread):
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
def run(self):
while self.program_running:
while self.running:
mouse.click(self.button)
time.sleep(self.delay)
time.sleep(0.1)
mouse = Controller()
click_thread = ClickMouse(delay, button)
click_thread.start()
def on_press(key):
if key == start_stop_key:
if click_thread.running:
click_thread.stop_clicking()
else:
click_thread.start_clicking()
elif key == exit_key:
click_thread.exit()
listener.stop()
with Listener(on_press=on_press) as listener:
listener.join()
经过一番研究,我了解了大部分内容,但我仍然对一件事感到困惑, 为什么即使没有任何调用,该类中的run()命令也会自动运行?此代码中没有其他“运行”
预先感谢
答案 0 :(得分:0)
这是典型的“线程”模式。您首先要子类化“ Thread”,然后重写run()
方法。
在此之后,您创建了该类的一个实例,该实例在此处显示:
click_thread = ClickMouse(delay, button)
click_thread.start()
“启动”方法启动使用“运行”功能的线程。因此有效“使run()
方法运行”的行是click_thread.start()
。
您可以在threading.Thread的文档中找到更多详细信息