why does my pyautogui code not works good - python

I create a simple script to find image on the desktop ,and type 'I found it ' ,and if I hide the image the script type 'I am unable to found it'.
the problem when I add another action ,which is I want the mouse move to the position of the image. the script works good ,but when I hide the image the mouse still move to the position ,and still type I found it. But normally the code should show me I am unable to found it.
the script still working on if instead to move to else.
my code is:
import pyautogui
import time
location = pyautogui.locateOnScreen('image.png', confidence = 0.6)
while 1:
if location:
print("I found it ")
time.sleep(2)
print(pyautogui.moveTo(location))
else:
print("I am unable to found it")

you store pyautogui.locateOnScreen('image.png', confidence = 0.6) in the variable location. Then you check the condition (if/else). But then you never recheck for pyautogui.locateOnScreen('image.png', confidence = 0.6). I am still not sure what you are trying to achieve here, but at least the check needs to go into the while:
while 1:
location = pyautogui.locateOnScreen('image.png', confidence = 0.6)
if location:
print("I found it ")
time.sleep(2)
print(pyautogui.moveTo(location))
else:
print("I am unable to find it")

Related

PyAutoGui While loop keep going when if statement remains true

I've just started learning python and started working on a project.
I'm moving my mouse cursor from one area to another. I just want it to stop when it reach a certain point/area/zone. I'm using the mouse position to tell me where it is, currently.
For some reason, when this loops starts, it keeps looping even when the IF statement is true.
But if I started when the IF statement is true, the loops kinda works as intended, so far it's only reading the 'X' values.
I couldn't find an answer to this, or any questions like it. If anyone has an idea or can point me to a similar post, I'll appreciate it.
import pyautogui, sys, time, autoit
#Search for a position on screen manually
try:
while True:
x, y = pyautogui.position()
print(pyautogui.position())
print('Stopping for 1 seconds, keep searching or CTRL + C to end')
time.sleep(1)
#Confirmed location on screen.
if pyautogui.position(x,y) >= pyautogui.position(710, 15):
pyautogui.leftClick()
print('The Eagle has landed')
print(pyautogui.position())
break
Update: I got it! Following mkrieger1 advice, I manage to get the 'x, y' values to update. Code was rewritten.

How to move pyautogui.prompt()?

When pyautogui.prompt() is called it displays a message box and it's always in the same spot. That box covers pictures I need to see, so I can write the right number. I need to move the box or make it invisible or minimize it or make it out of focus.
The problem is that you can't execute code while or after the message box is showing. The pyautogui.prompt is coded like this: pyautogui.prompt(text='', title='', default='', root=None, timeout=None). I know what each argument does, except root. The root argument doesn't accept boolean, integers, lists, strings, Point or tuple. It displays an error message: AttributeError: 'tuple' object has no attribute 'withdraw', if you put boolean, integers, lists, strings, Point or tuple in.
The only thing that root accepts is pyautogui.moveTo, pyautogui.dragTo and other mouse commands. Which are not that useful, because they execute before the box appears. Here is my code:
import pyautogui
selected_picture = int(pyautogui.prompt('Please write which picture to click on.',
'Select picture'))
if selected_picture == 1:
pyautogui.click(500,270)
if selected_picture == 2:
pyautogui.click(700,270)
if selected_picture == 3:
pyautogui.click(900,270)
Yes, I need to do it with pyautogui.prompt or some other message box. The original documentation doesn't even mention the root or timeout attribute and I can't find that information anywhere. I was trying something with tkinter, but I have no idea what it does.
I don't know if you want to change where the window appears or if you want to move it after it appears. If you just want to change the default window location, that can be done by importing pymsgbox and changing its rootWindowPosition value (the default value is "+300+200") and then every message box you put after that will appear at the new location.
import pyautogui as pag
import pymsgbox
pag.prompt(text="300,200") # appears at (300, 200)
pymsgbox.rootWindowPosition = "+500+500"
pag.prompt(text="500,500") # appears at (500, 500)
I couldn't find a way to move the prompt, so I did something easier. I just used IDLE.
import pyautogui
pyautogui.hotkey('alt','shift')
selected_picture = input()
pyautogui.hotkey('alt','shift')
if selected_picture == 1:
pyautogui.click(500,270)
if selected_picture == 2:
pyautogui.click(700,270)
if selected_picture == 3:
pyautogui.click(900,270)

How do I 'aim' an image at the mouse?

I'm starting out with python, I only know the basics and I want to create a top-down type of game to the one I have currently.
I've tried some solutions on the internet and sadly, none of them has worked for me.
As I said, I can't find a working solution as of right now but I've tried a few, including this one
How can I make the player “look” to the mouse direction? (Pygame / 2D).
I'm also using pygame, forgot to mention that. I also have pgzero if you need to know.
This code works and it just places a new actor when you click on it, but I want to have a type of 'character' with a weapon that can move around and 'look' at the mouse.
import pgzrun
from random import randint
apple = Actor("apple")
score = 0
def draw():
screen.clear()
apple.draw()
def place_apple():
apple.x = randint(10, 800)
apple.y = randint(10, 600)
def on_mouse_down(pos):
global score
if apple.collidepoint(pos):
print("Good Shot!")
place_apple()
score = score + 1
print(score)
else:
print("You Missed!")
quit()
pgzrun.go()
I just need to know how to make the picture 'look' at the cursor and then what each bit does to I know hot to do it for next time.
The first time I tried with the link given above, It returned a positional argument and I can't figure it out.
I may have messed something up when I put in the fixed code but I don't know, I was kind of tired.
I am not sure what exactly you mean with "aim at the mouse" but I guess you want to change the drawn image according to some program logic.
You do this simply setting the image property of the Actor to another picture, eg. when you click on the image, see my modified version of your
def on_mouse_down(pos):
global score
if apple.collidepoint(pos):
print("Good Shot!")
place_apple()
score = score + 1
apple.image = "cactus" # ADDED: Change the image if your click hit the Actor
print(score)
else:
print("You Missed!")
quit()
You can find the documentation of the complete API (function calls and properties) here:
https://pygame-zero.readthedocs.io/en/stable/builtins.html

How to get the coordinates after a mouse click?

I was using the following code to get the coordinates of a point after a mouse click (keep in mind I was clicking on a random point on the screen, not on a figure):
import win32api
posvals = [[],[]]
x = 0
state_left = win32api.GetKeyState(0x01)
while x<2:
a = win32api.GetKeyState(0x01)
if a != state_left:
state_left = a
print(a)
if a >= 0:
print('button down')
z,y = win32api.GetCursorPos()
posvals[x] = [z,y]
print(z,y)
x += 1
time.sleep(.001)
print(posvals)
Here I saved the coordinates in posvals, and the while loop is there because I only wanted to record 2 clicks. I got and tweaked this code from another question on stackoverflow, but I'm not sure which one.
My current problem is that I'm using a Linux computer and the win32api module (its official name is pywin32) won't work since it is only for windows.
How can I adjust (or completely restart) my code?
So there is no easy way to port the code to linux, unless you run in wrapped with WineLib or equivalent wrapper software. One such explanation of this practice is here.
You could try other mouse position packages like PyMouse. This might be a better option. This question also has some good examples of other more agnostic package options for python mouse coordinates.

How do I wait for pyautogui.locateonscreen() to return a value?

I am creating a webbot and I want to wait for a certain image to appear on the webpage before I continue my script.
I am making use of pyautogui.locatesonscreen() function, but I can't find a way to keep locating the object until it appears.
My script just seems to run the locateonscreen function once before it returns a value of none - I want it to keep looping untli it finds the image.
You can loop the script:
import pyautogui
image = pyautogui.locateOnScreen("image.png")
#Searches for the image
while image == None:
image = pyautogui.locateOnScreen("image.png")
print("still haven't found the image")
#When program finds image, print the location
print(image)
I know this post is two years old, but I found this asking the same questions and the provided solution does not work with pyautogui v0.9.41 and above. So here's my own:
import pyautogui
location = None
imageFile = 'image.png'
while (location == None):
try:
location = pyautogui.locateOnScreen(imageFile)
except Exception as e:
print(e)
print(location)
From pyautogui.readthedocs.io:
NOTE: As of version 0.9.41, if the locate functions can’t find the provided image, they’ll raise ImageNotFoundException instead of returning None.
Don't know why but the above solution is not working for me! maybe because it is looking for 100% match of the image, so to prevent this exception use confidence parameter! you can see more about it at PyAutoGUI’s documentation!
import pyautogui
import time
game_over =False
time.sleep(5)
while not game_over:
try:
x1, y1=pyautogui.center(pyautogui.locateOnScreen("./pyautogui_img/green_tik.JPG", confidence=0.7))
time.sleep(2)
pyautogui.moveTo(x1,y1)
print('Hurray! image found')
game_over = True
except:
print(f'image not found trying again in next 5 seconds. ')
time.sleep(5)
The above code is going to look for an image and if not found then going to try again in next 5 seconds, until the image not found it will keep running! and also to use it make sure you installed opencv and pillow too.

Categories