Search code examples
pythonlinuxxlib

How do I find which monitor the mouse pointer is in with python?


I have two monitors attached to my Desktop session in linux. I'd like to have a gtk window pop-up on the screen where the mouse cursor is. Sometimes it would be monitor 1, sometimes monitor 2. The pop-up is easy enough, but how can I determine which monitor contains the mouse pointer? I've run across various examples shelling out of python to call xrandr but I was hoping for a more integrative approach in Python.


Solution

  • Its pretty dependent on your setup which is why an "integrative" approach is fairly difficult. Multiple monitors on X is quite a mess.

    Assuming you are using twinview, the X screen is essentially just 1 screen anyway, so how does the monitor matter?

    from Xlib import display
    data = display.Display().screen().root.query_pointer()._data
    locationtuple = (data["root_x"], data["root_y"])
    

    That should work if you are using Twinview.