Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I track the mouse pointer over the entire screen in Python?

I wish to follow to mouse over the entire screen, not just limited to my GUI.

I used to be able to do it in C, and MATLAB, but now I'm working in Python and Tkinter.

like image 405
Well3 Avatar asked Dec 04 '25 23:12

Well3


2 Answers

Silly me -- it's really easy, you don't even need a GUI running.

import Tkinter as tk
root = tk.Tk()

root.winfo_pointerx()  # this returns the absolute mouse x co-ordinate.
like image 95
Well3 Avatar answered Dec 07 '25 19:12

Well3


Try the below sample code it will help to get you a better understanding

import Tkinter as tk
import Xlib.display as display

def mousepos(screenroot=display.Display().screen().root):
    pointer = screenroot.query_pointer()
    data = pointer._data
    return data["root_x"], data["root_y"]

def update():
    strl.set("mouse at {0}".format(mousepos()))
    root.after(100, update)

root = tk.Tk()
strl = tk.StringVar()
lab = tk.Label(root,textvariable=strl)
lab.pack()
root.after(100, update)
root.title("Mouseposition")
root.mainloop()

Also please comment if you have any doubts .

like image 39
coder3521 Avatar answered Dec 07 '25 19:12

coder3521



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!