I'm new to python and I'm working on a small autoclicker that you can turn on & off using the letter 's', however when I press it the autoclicker starts but I can't turn it off unless I use the letter 'k' which is used to stop the program completely, this is what my code looks like:
from pynput.mouse import Controller, Button
import keyboard as kb
import time
import multiprocessing
def click():
isToggled = False
mouse = Controller()
while True:
if isToggled:
mouse.click(Button.left)
time.sleep(0.01)
if kb.is_pressed('s'):
if isToggled:
isToggled = False
else:
isToggled = True
elif kb.is_pressed('k'):
break
if __name__ == '__main__':
p = multiprocessing.Process(target=click)
p.start()
p.join()
CodePudding user response:
This happens because as long as s
is held down, kb.is_pressed('s')
will evaluate to True
. So isToggled
will rapidly toggle between True
and False
until you release the key, and it's anyone's guess what value it will be.
One way you could solve this is to basically lock isToggled
from being set more than once until s
is released. Something like this:
key_locked = False
while True:
...
if kb.is_pressed('s'):
if key_locked:
continue
key_locked = True
if isToggled:
isToggled = False
else:
isToggled = True
else:
key_pressed = False
if kb.is_pressed('k'):
break
CodePudding user response:
The issue is that the kb.is_pressed('s')
function returns true while the key is being held, so every time the while loop runs isToggled
is geting flipped and because if isToggled
is true there is a sleep, it is more likely that when you release the key, you end up with this value.
You can fix that by adding another variable that stores if the key was pressed in the last iteration and only flip the isToggled
if it was not. Also as a side note, the fliping of the isToggled
variable can be simplified a bit. The updated code could look like this:
from pynput.mouse import Controller, Button
import keyboard as kb
import time
import multiprocessing
def click():
isToggled = False
wasPressed = False
mouse = Controller()
while True:
if isToggled:
mouse.click(Button.left)
time.sleep(0.01)
if kb.is_pressed('s'):
if not wasPressed:
isToggled = not isToggled
elif kb.is_pressed('k'):
break
wasPressed = kb.is_pressed('s')
if __name__ == '__main__':
p = multiprocessing.Process(target=click)
p.start()
p.join()