Не работает pyautogui position

Добро пожаловать на страницу перевода документации по PyAutoGUI!¶

API разработан таким образом, чтобы быть простым. PyAutoGUI работает в Windows, macOS и Linux, и поддерживает Python 2 и 3.

Для установки, выполните pip install pyautogui . Смотрите страницу установки для получения подробной информации.

В PyAutoGUI имеются следующие функции:

  • Перемещение и нажатие кнопок мыши в окнах других приложений .
  • Отправка нажатий клавиш в приложения( например, для заполнения форм)
  • Делать скриншоты и читать изображения (например, кнопку или чекбокс) и находить его на экране.
  • Находить окна приложений, перемещать , изменять размер, максимизировать, минимизировать или закрыть их (на данный момент, только в Windows).
  • Показывать диалоговые окна для предупреждений и сообщений.

Вот видео на YouTybe, как бот играет в игру Sushi Go Round. Бот наблюдает за окном приложения игры и ищет изображения суши-заказов. Когда он находит один, он нажимает на ингредиенты, чтобы сделать суши. Он также кликает по телефону в игре, чтобы заказать больше ингредиентов по мере необходимости. Бот полностью автономный и может завершить все семь дней игры. Это тот вид автоматизации, на который способен PyAutoGUI.

Примеры¶

Этот пример перемещает мышь в виде квадратной спирали в MS Paint(или любой другой программе для рисования)

Преимущество использования PyAutoGUI, в отличие от скрипта, который непосредственно генерирует файл изображения, заключается в том, что вы можете использовать инструменты кисти, которые предоставляет MS Paint.

FAQ: Часто задаваемые вопросы:¶

Q: Может ли PyAutoGUI работать на Android, iOS или планшете/телефоне

A: К сожалению нет. PyAutoGUI работает только на Windows, macOS и Linux.

Q: Работает ли PyAutoGUI с несколькими мониторами.

A: Нет, сейчас PyAutoGUI работает только с основным монитором.

Q: PyAutoGUI распознает символы на изображении(OCR)?

A: Нет, но это возможно появится в будущем.

Q: Может ли PyAutoGUI логировать клавиши, или определять, нажата ли клавиша в данный момент?

A: Нет, PyAutoGUI не может делать это сейчас.

Fail-Safes¶

Like the enchanted brooms from the Sorcerer’s Apprentice programmed to keep filling (and then overfilling) the bath with water, a bug in your program could make it go out of control. It’s hard to use the mouse to close a program if the mouse cursor is moving around on its own.

As a safety feature, a fail-safe feature is enabled by default. When a PyAutoGUI function is called, if the mouse is in any of the four corners of the primary monitor, they will raise a pyautogui.FailSafeException . There is a one-tenth second delay after calling every PyAutoGUI functions to give the user time to slam the mouse into a corner to trigger the fail safe.

You can disable this failsafe by setting pyautogui.FAILSAFE = False . I HIGHLY RECOMMEND YOU DO NOT DISABLE THE FAILSAFE.

This documentation is still a work in progress.

Источник

Читайте также:  Не работает кнопка вставить при копировании

Как решить проблемы с pyautogui?

Я написал небольшой код в 2 строчки:

Когда запустил, получил ошибку:

  • Вопрос задан 14 июл.
  • 1092 просмотра

Версию Python понижать не нужно. Нужно понизить версию самого модуля pyautogui
Это можно сделать с помощью этой команды: pip install PyAutoGUI==0.9.52

Видимо в версии 0.9.53 кто-то где-то накосячил.

Лев Барях, да я ж не знаю что у Вас там по написано.

В ошибке пишет:
import pyautogui as pg

Чего у Вас там еще интересного?!

pyautogui у меня установлен:

До этой ошибки баловались с другими модулями, типа захвата изображения?

Если посмотреть файл модуля pyautogui/__init__.py, там есть 225 строка, там текст «# If pyscreeze module is not found, screenshot-related features will simply not work.» (# Если модуль pyscreeze не найден, функции, связанные со снимками экрана, просто не будут работать.)

Источник

Проблемы с использованием pyautogui

Пытаюсь использовать функцию pyautogui.locateOnScreen и подобные ей pyautogui.locateAllOnScreen и pyautogui.locateCenterOnScreen .

После исполнения этого кода Python ничего не делает, не двигает, не кликает и не выписывает ошибку. Изображение ‘test6.png’ это изображение иконки меню действий на StackOverflow (). Изображение обрезал максимально, но так, чтобы было понятно, что это меню. С разными вариантами функции pyautogui.locateOnScreen тоже возникают разные ошибки:

Видимо тип данных, которые присылаются в эту функцию не соответствует тем, которые нужны. Но в документации всё работало

– просто молчит, и ничего не происходит. Когда я пытаюсь кликнуть по тому изображению с помощью функции pyautogui.click, которое оно как бы нашло, то ничего не происходит: ни клика, ни ошибки.

Python пишет None, но в примерах из документации Pyautogui все эти функции работали и Python писал либо координаты ‘x, y’ либо кортеж из значений высоты, ширины, отступа слева и сверху.

OpenCV для Python у меня установлен, функция pyautogui.locateAllOnScreen его не видит и всё равно использует pyscreeze. Нужно ли импортировать OpenCV или он должен использоваться сам? Никакие окна у меня не закрывают иконку, и браузер я мышкой не двигаю. В чем проблема никак понять не могу.

Версии: python 3.5.2, pyscreeze 0.1.26, OpenCV 4.2, pyautogui 0.3.1

Источник

Mouse Control FunctionsВ¶

The Screen and Mouse PositionВ¶

Locations on your screen are referred to by X and Y Cartesian coordinates. The X coordinate starts at 0 on the left side and increases going right. Unlike in mathematics, the Y coordinate starts at 0 on the top and increases going down.

The pixel at the top-left corner is at coordinates 0, 0. If your screen’s resolution is 1920 x 1080, the pixel in the lower right corner will be 1919, 1079 (since the coordinates begin at 0, not 1).

The screen resolution size is returned by the size() function as a tuple of two integers. The current X and Y coordinates of the mouse cursor are returned by the position() function.

Here is a short Python 3 program that will constantly print out the position of the mouse cursor:

Here is the Python 2 version:

To check if XY coordinates are on the screen, pass them (either as two integer arguments or a single tuple/list arguments with two integers) to the onScreen() function, which will return True if they are within the screen’s boundaries and False if not. For example:

Читайте также:  Ноутбук hp g62 не работает hdmi

Mouse MovementВ¶

The moveTo() function will move the mouse cursor to the X and Y integer coordinates you pass it. The None value can be passed for a coordinate to mean “the current mouse cursor position”. For example:

Normally the mouse cursor will instantly move to the new coordinates. If you want the mouse to gradually move to the new location, pass a third argument for the duration (in seconds) the movement should take. For example:

(If the duration is less than pyautogui.MINIMUM_DURATION the movement will be instant. By default, pyautogui.MINIMUM_DURATION is 0.1.)

If you want to move the mouse cursor over a few pixels relative to its current position, use the move() function. This function has similar parameters as moveTo() . For example:

Mouse DragsВ¶

PyAutoGUI’s dragTo() and drag() functions have similar parameters as the moveTo() and move() functions. In addition, they have a button keyword which can be set to ‘left’ , ‘middle’ , and ‘right’ for which mouse button to hold down while dragging. For example:

Tween / Easing FunctionsВ¶

Tweening is an extra feature to make the mouse movements fancy. You can probably skip this section if you don’t care about this.

A tween or easing function dictates the progress of the mouse as it moves to its destination. Normally when moving the mouse over a duration of time, the mouse moves directly towards the destination in a straight line at a constant speed. This is known as a linear tween or linear easing function.

PyAutoGUI has other tweening functions available in the pyautogui module. The pyautogui.easeInQuad function can be passed for the 4th argument to moveTo() , move() , dragTo() , and drag() functions to have the mouse cursor start off moving slowly and then speeding up towards the destination. The total duration is still the same as the argument passed to the function. The pyautogui.easeOutQuad is the reverse: the mouse cursor starts moving fast but slows down as it approaches the destination. The pyautogui.easeOutElastic will overshoot the destination and “rubber band” back and forth until it settles at the destination.

These tweening functions are copied from Al Sweigart’s PyTweening module: https://pypi.python.org/pypi/PyTweening https://github.com/asweigart/pytweening This module does not have to be installed to use the tweening functions.

If you want to create your own tweening function, define a function that takes a single float argument between 0.0 (representing the start of the mouse travelling) and 1.0 (representing the end of the mouse travelling) and returns a float value between 0.0 and 1.0 .

Mouse ClicksВ¶

The click() function simulates a single, left-button mouse click at the mouse’s current position. A “click” is defined as pushing the button down and then releasing it up. For example:

To combine a moveTo() call before the click, pass integers for the x and y keyword argument:

To specify a different mouse button to click, pass ‘left’ , ‘middle’ , or ‘right’ for the button keyword argument:

Читайте также:  Как починить наручные часы которые не ходят

To do multiple clicks, pass an integer to the clicks keyword argument. Optionally, you can pass a float or integer to the interval keyword argument to specify the amount of pause between the clicks in seconds. For example:

As a convenient shortcut, the doubleClick() function will perform a double click of the left mouse button. It also has the optional x , y , interval , and button keyword arguments. For example:

There is also a tripleClick() function with similar optional keyword arguments.

The rightClick() function has optional x and y keyword arguments.

The mouseDown() and mouseUp() FunctionsВ¶

Mouse clicks and drags are composed of both pressing the mouse button down and releasing it back up. If you want to perform these actions separately, call the mouseDown() and mouseUp() functions. They have the same x , y , and button . For example:

Mouse ScrollingВ¶

The mouse scroll wheel can be simulated by calling the scroll() function and passing an integer number of “clicks” to scroll. The amount of scrolling in a “click” varies between platforms. Optionally, integers can be passed for the the x and y keyword arguments to move the mouse cursor before performing the scroll. For example:

On OS X and Linux platforms, PyAutoGUI can also perform horizontal scrolling by calling the hscroll() function. For example:

The scroll() function is a wrapper for vscroll() , which performs vertical scrolling.

© Copyright 2019, Al Sweigart Revision 24d638dc .

Источник

Pyautogui не выводит буквы

будет выведено
://../2048

при этом буквы не выводятся, но 0.2 с ожидания на вывод буквы проходят (надеюсь, понятно сказал), при вбивании в google нашло ошибку (https://github.com/asweigart/pyautogui/issues/46), т. е. работает только при английской раскладке (не eng-rus).

Поэтому вопрос: возможно ли как-то временно изменить раскладку клавиатуры (только при запуске программы) или есть ли какая-то простая альтернатива для

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Pyautogui не кликает
Здравствуйте. Суть: скрипт должен нажимать в одну область, вводить определенный текст, после.

Ошибка ModuleNotFoundError: No module named ‘pyautogui’ при импорте pyautogui
Все установлено, но при импорте модуля выдает ошибку. С чем это может быть связано? pip install.

pyAutoGUI
тестирую функции pyAutoGUI для одного проекта тестирую функцию locateOnScreen кто хорошо знает.

Программа с PyAutoGui в цикле
Когда делал программу на PYTHON с библиотекой PyAutoGui столкнулся с небольшой проблемкой. Когда я.

другое дело, что это не поможет.

Из подобных pyautogui токмо pywinauto знаком мне, и оно работает

Если системный язык — русский, а напечатать нужно латиницу, раскладку менять необходимо дважды: для потока питонячьего скрипта и для окна в которое собираетесь втыкнуть латинское безобразие (с русского на английский, конечно).

Вертаю долг. Бессмысленный, правда

Interval в pyautogui
Здраствуйте! Написал следующий код: from tkinter import * from pyautogui import * def.

Проблемы с Pillow (я так думаю) в pyautogui
Пишу: import pyautogui pyautogui.screenshot() Выдает: Traceback (most recent call last).

Не выводит русские буквы
Всем привет. Начал постигать азы C++ и столкнулся с проблемой. Когда запускаешь программу вместо.

Источник

Оцените статью