我正在制作一个自动答题器,它用“ e”关闭和打开,但之后 它打开但没有关闭。
我曾尝试多次更改代码,但仍然找不到 问题。
import pynput
from pynput.keyboard import KeyCode, Listener
from pynput.mouse import Button, Controller
import time
mouse = Controller()
def onoff(keycode, on=None):
rkey = str(keycode).strip("'")
if rkey == "e":
if not on:
print("on")
on = True
elif on:
print("off")
on = False
if not on:
print("not on")
elif on:
while on:
mouse.click(Button.left)
time.sleep(0.4)
with Listener(on_press=onoff) as l:
l.join()
我希望它在按“ e”后会关闭,但一直保持点击状态。
答案 0 :(得分:0)
您的意思不是很清楚,因为Pynput中的Listener
是新的thread
。如果需要停止该线程,则线程中的while True任务将相应停止。它们应该彼此分开。再次按下“ e”后,使用.join()
方法关闭键盘监听功能并保持点击状态,请尝试下面的代码以查看是否要获得效果:
from pynput.keyboard import Listener
from pynput.mouse import Button, Controller
import time
import threading
mouse = Controller()
class Demo:
def __init__(self):
self.key_list = []
self.c = threading.Thread(target=self.click)
self.l = Listener(on_press=self.onoff)
self.l.start()
self.l.join()
def click(self):
while True:
mouse.click(Button.left)
time.sleep(0.4)
def onoff(self, key):
try:
key_str = key.char
except AttributeError:
key_str = key.name
if key_str == "e":
if len(self.key_list) == 0:
self.key_list.append(key_str)
self.c.start()
elif key_str in self.key_list:
self.l.stop()
print('Keyboard listen stopped')
print('Mouse click continue')
self.c.join()
Demo()