0

Is there a way to constantly get my mouse position and print it with Python? I know that with Tkinter you can achieve that by binding mouse motion with something like this, but i want something that also works outside of Tkinter created windows

def motion(event):
    posx, posy = pyautogui.position()
    print("PosX = " + str(posx) + " PosY = " + str(posy))
root.bind('<Motion>', motion)

Edit: Thanks for the answers but i wasn't so clear in my question, i need a way it works on background while i can use other methods on my code. If i use while True i will be locked within this method. I need something exactly like root.bind('<Motion>', motion) but that works outside of root window, for example.

4 Answers4

4

You can use after() and winfo_pointerxy() to get the mouse position constantly:

import tkinter as tk

root = tk.Tk()

lbl = tk.Label(root, width=20)
lbl.pack()

def get_mouse_pos():
    lbl.config(text='{}, {}'.format(*root.winfo_pointerxy()))
    root.after(100, get_mouse_pos)

get_mouse_pos()
root.mainloop()
acw1668
  • 40,144
  • 5
  • 22
  • 34
1

You can do that in very simple way. You will need pyautogui

import pyautogui

while True:
    print(pyautogui.position())

Output :

Point(x=708, y=380)
Philip Purwoko
  • 407
  • 5
  • 20
0

Try this it may help you

#!/usr/bin/python

import struct
import binhex

# You'll need to find the name of your particular mouse to put in here...
file = open("/dev/input/by-id/usb-Logitech_USB_Trackball-event-mouse","rb")


while True:
     byte = file.read(16)
#    h = ":".join("{:02x}".format(ord(c)) for c in byte)
#    print "byte=",h

    (type,code,value) =  struct.unpack_from('hhi', byte, offset=8)

    if type == 1 and value == 1:
        if code == 272:
            print ("LEFT PRESS")
        if code == 273:
            print("RIGHT PRESS")

    if type == 2:
        if code == 0:
            print("MOVE L/R",value)
        if code == 1:
            print("MOVE U/D",value)
Ujjwal Dash
  • 767
  • 1
  • 4
  • 8
0

Managed to do it by using the pyxhook library (implementation of pyhook for Linux). By using this solution you will not have the disadvantage that you are locked on a while True loop. To stop the capture just press 'Esc' (event.Ascii == 27).

import pyxhook
import pyautogui

def mouse_event(event):
    posx, posy = pyautogui.position()
    print ("PosX: " + str(posx) + ", PosY: " + str(posy))

def cancel_hookmanager(event):
    if event.Ascii == 27:
        hookman.cancel()

hookman = pyxhook.HookManager()
hookman.MouseMovement = mouse_event
hookman.KeyUp = cancel_hookmanager
hookman.HookKeyboard
hookman.HookMouse
hookman.start()