pythonpython-3.xkeyboardpyautoguimouse-position

writing live mouse position and RGB using python


I'm trying to make a hotkey that when i click in some other program (while script running) a hotkey "1" for example or any other key i assign that it write down the mouse positions and RGB in a text file a single time without spamming it and here is the closest code i could found that at least print the result of mouse position but it doesn't get the colors "RGB"

import pyautogui
import time
import keyboard

c = open("log.txt", "w")
def a():
   while True:
        if keyboard.read_key() == "1":
            x, y = pyautogui.position()
            positionStr = str(x).rjust(4) + str(y).rjust(4)
            print(positionStr)
            c.write(positionStr + '\n')
            c.flush()
            time.sleep(0.1)
        else:
              a()
a()

how ever i did find out that one codepyautogui.displayMousePosition() that do show xy and also RGB but im a beginner script kid that have no idea how to save the results to any .txt file

side note: the shown code is copied from some other answer here "https://stackoverflow.com/questions/64046117/write-mouse-position-to-txt-file" and just made the hotkey edit part

and i tried to get it done with myself like this:

c = open("log.txt", "w")

def b(): pyautogui.displayMousePosition()

def a():
    while True:
        if keyboard.read_key()== '1':
            print(b())
            c.write(b())
            c.flush()
            sleep(1)
        else:
            a()
a()

but it just stuck in the print(b()) command like in a infinite loop showing live xy and RGB but not saving it and when doing ctrl+c it dont save


Solution

  • ok guy i figured it out

    c = open("log.txt", "w")
    def a():
     while True:
        if keyboard.is_pressed('1'):
            x, y = pyautogui.position()
            r,g,b = pyautogui.pixel(x,y)
            positionsANDrgb = str(r).rjust(4)+str(g).rjust(4)+str(b).rjust(4)
            print(positionsANDrgb)
            c.write(positionsANDrgb+'\n')
            c.flush()
            sleep(1)
    a()
    i had to add the "sleep(1)" cuz in my single press takes some time like 2third of a second or something like that and command spam as long as i was pressing the hot key and the '\n' part means new line u can name the "positionsANDrgb" any thing u want but i just chose this name to make it easier to know what this name for u dont need the print(positionsANDrgb) part it dont have anything to do with the log.txt but i just added it to see when command is active and "rjust(4)" it adds 4 character of what ever u choose(default is sapce) like "rjust(4,'b')" supposed to give 4 b's sometimes it dont work just increase the 4 till it do in case u wanted it in future i hope this helped u there who ever needed this like me