Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I toggle a boolean based on keyboard input?

So, I'm trying to create a simple autoclicker in python, just for fun. I've downloaded and experimented with two libraries, PYAutoGUI and Keyboard. I can turn on the autoclicker, but can't turn it off. I want to make it so that whenever I press the key on my keyboard, it toggles the autoclicker from on to off or vice versa. For some reason, it doesn't do this. Is there something I'm missing or am I just a newbie at python? Here is my code:

import pyautogui
import keyboard

shouldClick = False
while True:
    if keyboard.is_pressed('z'):
        shouldClick = not shouldClick
    if shouldClick == True:
        pyautogui.click()
like image 717
Lowell Justice Avatar asked Dec 05 '25 00:12

Lowell Justice


1 Answers

Here's my answer to my own question:

import pyautogui
import keyboard

shouldClick = False
keyRelease = True

while True:
    if keyboard.is_pressed('z') and keyRelease:
        keyRelease = False
        shouldClick = not shouldClick
    if not keyboard.is_pressed('z'):
        keyRelease = True
    if shouldClick:
        pyautogui.click()

Yes, I do tend to ask questions and then figure out the answers myself. It seems I just had to add in a boolean that checks whether I'd pressed the key that instance.

like image 126
Lowell Justice Avatar answered Dec 06 '25 12:12

Lowell Justice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!