Search code examples
pythonpynput

Why do I always have the error message Controller has no attribute is_pressed?


I've been coding a very simple autoclicker. My autoclicker works just fine, but the only way to kill it is forcefully shut down my computer because it clicks so fast I can't access my taskbar. I could make it slower, but I'd prefer a way for the user to close the autoclicker with the press of a button. I've tried if keyboard.is_presssed('q'): break but I always get the error message AttributeError: 'Controller' object has no attribute 'is_pressed'. Did you mean: 'alt_pressed'? I expected my code to break the loop when I press q, but instead I get an error message. The error message will also pop up without the pressing of q. My code as of now is:

from pynput.mouse import Button, Controller
from pynput.keyboard import Key, Controller
import time

keyboard = Controller()
mouse = Controller()


while True:
    time.sleep(10)
    mouse.click(Button.left)
    if keyboard.is_pressed('q'):
        break

Solution

  • pynput doesn't have is_pressed() - I don't know where you find it.

    You should rather use pynput.keyboard.Listener to run code when q is pressed and set some variable - q_is_pressed = True - or run code which ends program.


    You can't have two objects with the same name Controller.

    One Controller replaces other Controller and later you use the same Controller to create mouse and keyboard - and this makes problem.

    You have to use pynput.mouse.Controller and pynput.keyboard.pynput.Controller

    import pynput
    from pynput.mouse import Button
    from pynput.keyboard import Key
    import time
    
    keyboard = pynput.keyboard.Controller()
    mouse    = pynput.mouse.Controller()
    
    while True:
        time.sleep(10)
        mouse.click(Button.left)
        #if keyboard.is_pressed('q'):  # <-- this will need Listener()
        #    break
    

    EDIT:

    To end code when q was pressed you have to use Listener

    For example:

    import pynput
    from pynput.mouse import Button
    import time
    
    mouse_controller = pynput.mouse.Controller()
    
    def on_press(key):
        print('pressed:', key)
        if str(key) == "'q'":  # it has to be with `' '` inside `" "`
            # Stop listener
            print("exit listener")
            return False  # `False` ends listener
    
    with pynput.keyboard.Listener(on_press=on_press) as keyboard_listener:
        
        while keyboard_listener.is_alive():
            time.sleep(10)
            mouse_controller.click(Button.left)
            print('clicked')