Search code examples
pythonmousepyautoguitween

Python unable to use PyAutoGui tween to move mouse as random value in a function


I am trying to use a random tween function from pyautogui to randomly move the mouse. I made a list of these functions and using random.choice() to randomly select one to use in my loop. I cant figure out why it wont work.

import pyautogui as p
import random

game_window = 'game.png'
games = p.locateAllOnScreen(game_window, confidence=0.8,
                            region=(0, 1400, 3000, 40))
mouse_random_moves = ('p.easeOutCubic', 'p.easeOutQuint', 'p.easeInQuart',
                        'p.easeInOutBounce', 'p.easeInOutBack', 'p.easeInCubic',)

for game in games:
    move = random.choice(mouse_random_moves)
    left, top, width, height = game
    click_window = p.center(game)
    x, y = click_window
    p.moveTo(x, y, duration=1, tween=move)

I get an error:

Traceback (most recent call last):
  File "C:\Users\rysik\Documents\python_work\test\test.py", line 15, in <module>
    p.moveTo(x, y, duration=1, tween=move)
  File "C:\Users\rysik\Documents\python_work\test\venv\lib\site-packages\pyautogui\__init__.py", line 598, in wrapper
    returnVal = wrappedFunction(*args, **kwargs)
  File "C:\Users\rysik\Documents\python_work\test\venv\lib\site-packages\pyautogui\__init__.py", line 1283, in moveTo
    _mouseMoveDrag("move", x, y, 0, 0, duration, tween)
  File "C:\Users\rysik\Documents\python_work\test\venv\lib\site-packages\pyautogui\__init__.py", line 1483, in _mouseMoveDrag
    steps = [getPointOnLine(startx, starty, x, y, tween(n / num_steps)) for n in range(num_steps)]
  File "C:\Users\rysik\Documents\python_work\test\venv\lib\site-packages\pyautogui\__init__.py", line 1483, in <listcomp>
    steps = [getPointOnLine(startx, starty, x, y, tween(n / num_steps)) for n in range(num_steps)]
TypeError: 'str' object is not callable

However, if I just assign a tween function to a variable then it works. This will move the mouse:

mouse = p.easeOutBack
p.moveTo(x, y, duration=1, tween=mouse)

Any idea on what is causing the error?


Solution

  • The variabel mouse_random_moves has string values. In your mouse example it's not a string value but a function. Remove the single quotes in your mouse_random_moves values.

    Can you try the following code:

    import pyautogui as p
    import random
    
    game_window = 'game.png'
    games = p.locateAllOnScreen(game_window, confidence=0.8,
                                region=(0, 1400, 3000, 40))
    mouse_random_moves = (p.easeOutCubi, p.easeOutQuint, p.easeInQuart,
                            p.easeInOutBounce, p.easeInOutBack, p.easeInCubic)
    
    for game in games:
        move = random.choice(mouse_random_moves)
        left, top, width, height = game
        click_window = p.center(game)
        x, y = click_window
        p.moveTo(x, y, duration=1, tween=move)