Can't run pyautogui comands in Python programs

D:\reshala>python reshala3.py
Traceback (most recent call last):
File “D:\reshala\reshala3.py”, line 26, in
if check_pixel_color(field_x, field_y, expected_color):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “D:\reshala\reshala3.py”, line 10, in check_pixel_color
pixel_color = pyautogui.pixel(x, y)
^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\ekvnd\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\pyautogui_init_.py”, line 228, in _couldNotImportPyScreeze
raise PyAutoGUIException(
pyautogui.PyAutoGUIException: PyAutoGUI was unable to import pyscreeze. (This is likely because you’re running a version of Python that Pillow (which pyscreeze depends on) doesn’t support currently.) Please install this module to enable the function you tried to call.

BUT
Python, Pillow, pyautogui, pyscreeze are the at the most recent versions , computer is restarted but this error still appears and python programm don’t work.

It’s best to post code and errors inside markers so they come out readable

I was thinking that:

seems to give you the most likely problem pretty well, your Python is too new, but both products claim to work with 3.12. So I don’t know.

If I had to dig into it, I would probably try simple examples from PyScreeze so as to simplify the problem, and maybe pyscreeze will tell you why it doesn’t import, rather than PyAutoGUI’s guess.

2 Likes

Okay windows cmd doesn’t type that message in anymore but the program doesn’t do anything after being lauched. I don’t know what’s wrong with my laptop or the code. I’m so confused.

import pyautogui
import time

# Функция для проверки цвета пикселя
def check_pixel_color(x, y, expected_color):
    pixel_color = pyautogui.pixel(x, y)
    return pixel_color == expected_color

field_x = 450
field_y = 810
expected_color = (56,22,22)


n = 1
max_n = 50

# Пока n меньше или равно максимальному значению
while n <= max_n:
    # Проверяем цвет поля
    if check_pixel_color(field_x, field_y, expected_color):
        # Увеличить значение n
        n += 1
        # Перемещаем курсор в поле
        pyautogui.click(307, 705)
        pyautogui.click(307, 705)        
        # Очищаем поле
        pyautogui.hotkey('ctrl','a')       
        pyautogui.press('delete')

        # Вставить новое значение n
        pyautogui.typewrite(str(n))

        # Переходим к следующему полю
        pyautogui.click(420, 850)
        
        # Переходим к началу следующей итерации цикла
        continue
    
   
    break
  1. Does the field is where these coordinates are pointing?
  2. Are you trying to simulate a double click?
1 Like

Okay that’s so weird. The original code :

import pyautogui
import time

# Максимальное значение для n
max_n = 50

# Функция для проверки цвета пикселя
def check_pixel_color(x, y, expected_color):
    pixel_color = pyautogui.pixel(x, y)
    return pixel_color == expected_color

field_x = 475
field_y = 805
expected_color = (56,22,22)

# Начальное значение n
n = 1

# Максимальное значение для n
max_n = 50

# Пока n меньше или равно максимальному значению
while n <= max_n:
    # Проверяем цвет поля
    if check_pixel_color(field_x, field_y, expected_color):
        # Увеличить значение n
        n += 1
        # Перемещаем курсор в поле
        pyautogui.click(471, 274)
        pyautogui.click(471, 274)
        # Очищаем поле
        pyautogui.hotkey('ctrl','a')       
        pyautogui.press('delete')
        # Вставить новое значение n
        pyautogui.typewrite(str(n))
      # Переходим к следующему полю (может потребоваться для срабатывания изменений)
        pyautogui.click(634, 1050)
        
        # Переходим к началу следующей итерации цикла
        continue
    
    # Если цвет поля не соответствует ожидаемому, выходим из цикла
    break)

This is original code . It worked a week ago. I’ve (no making mistakes) changed the fields and places to click only. Today the python in cmd couldn’t start any command from pyautogui, so I updated Windows, Python, Pillow, pyautogui, pyscreeze and then I’ve tried to start a program. The cmd said nothing, just

D:\reshala>python reshala.py

D:\reshala>python reshala.py

D:\reshala>python reshala.py

Then I’ve added print “Hello world” after each step and realized that The steps up to while n <= max_n: are played. So I deleted this stroke and cmd writes me about my mistakes

if check_pixel_color(field_x, field_y, expected_color): IndentationError: unexpected indent

    continue
    ^^^^^^^^
SyntaxError: 'continue' not properly in loop

So now I’m trying to find correct places (number of Tabs) for continue and if

This is so fucking weird , I was should only change coordinates of clicking and the field
I think I should hire the sysadmin.
I can tell my story in more details in my discord @vladbulayev

  1. Yes, it is coloured with (56,22,22)
    2)I know that looks illogical but without doubleclick the previous n won’t disappear and the pasted number will increase by the previous as 123456789101112131415161718192021 and so on.

Um, your code was mangled. Please edit your post, as now it is unreadable (and calm down, we will macgyver something from it :wink: )

As for double click: there is a method pyautogui.doubleClick( coord_x, coord_y ) that does that right.

Well, in Python indentation matters. When you removed that line, the rest code that belonged to the while statement should also be shifted left by one indentation level. Also continue outside of a loop is a grammar error, so it should be removed too.

Also: I see you have import-ed a time package. Make use of this package, as maybe your program simply works too fast :slight_smile:

3 Likes

Thanks for tellin about pyautogui.doubleClick( coord_x, coord_y ) !
Thanks for telling about shifting and “continue” !
I’ve imported time package because I used time.sleep(...). Now it’s useless.
Noo, the weak ago algorithm was working and too slow ~60000 different n per night. Mixiing to same pyautogui.click to one command will increase sped of counting Ns for 20% maybe. I even want to rewrite algorithm to another program language because Python is slow for all tasks you know.

Okay, after I reread you code again, I’ve found something:

You’ve said You tested the code and found out it “stops” at this moment. Well, the code should work unless that check_pixel_color function really returns False. If that was the case then your code indeed was run without problems and without your code inside that if statement.

I imagine it this way: you start your program by typing python reshala.py in a terminal. Because, as I said, your program works fast, then you are not quick enough to move the terminal “out of the program way”, so it checks very fast the pixel color (which it contains the terminal color) at these coords. Because it is not what your program expects, the function check_pixel_color returns False and nothing further is called at all.

My recommendation would be then You should add a time.sleep(5) at the beginning, so you, after starting your program, will have got 5 seconds to move away any window that covers the window you are interested in.

1 Like

I want to hug you, my dear. I didn’t expect so much help from the internet

1 Like

:hugs:

So, it worked?

not yet. fixing “IndentationError: unexpected indent” in different lines

There may be another bug in this code:

pixel_color = pyautogui.pixel(x, y)
return pixel_color == expected_color

I spot that after I’ve read the pyautogui documentation. In the docs they say pyautogui.pixel(...) doesn’t return a tuple but some special object of their sort. I can bet my entire money in my wallet that if you change the return ... instruction into:

ret = pixel_color == expected_color
print(ret)
return ret

Then you will got in your terminal 50 lines with False text (of course after you fix that IndentationError :wink: )

1 Like

OMG THE MOUSE STARTED TO MOVE OMG!
(after adding waiting 5 seconds by your advise )

now only have to remove grammar mistakes and bugs. I was believing that python or something other ignores pyautogui

1 Like

The easiest method to me to know coordinates is using print (pyautogui.position()) . Thanks to this indian guy. Idk why people download additional programs or write scripts on java and python

omg I figured out why the python program was doing nothing, because the rgb 56,22,22 field was at another position. I used Определение координат курсора мыши · Блог веб-студии Keengo to find coordinates which gives the wrong answer. You in the beginning was right. FACEPALM

Now everything works as a week ago.
As you asked I’ve added

  1. time.sleep(5) pyautogui.click(550, 670) (into beginning)

  2. doubleclick

and everything exept coordinates to click and the field is the same as the “original code” in the third post in our today’s forum. I didn’t read anything about Can't run pyautogui comands in Python programs - #14 by FelixLeg but will do it now, maybe it’ll help me in the future.

and I figured out why I was need for two click. Because pyautogui.hotkey('ctrl','a') doesn’t work in my code and doubleclick = ‘ctrl’,‘a’