pythonscreenpygtkgdk

How to get total screen size in Python / GTK without using deprecated Gdk.Screen.get_width()?


I want the X/Y pixel dimensions of the entire desktop (potentially spanning multiple monitors), e.g. to determine the optimal resolution of a background image.

This Python code still works:

from gi import require_version
require_version("Gdk", "3.0")
from gi.repository import Gdk
screen = Gdk.Screen.get_default()
print(screen.get_width(), " ", screen.get_height())

but prints a deprecation warning:

<string>:7: DeprecationWarning: Gdk.Screen.get_width is deprecated
<string>:7: DeprecationWarning: Gdk.Screen.get_height is deprecated

The Gdk.Screen API docs just note:

Deprecated since version 3.22: Use per-monitor information instead

Other answers (like How do I get monitor resolution in Python or How to detect a computer's physical screen size in GTK) mention lots of other APIs and toolkits, or just give per-monitor information (like this for PyGtk), but I think it should still be possible (also in the future) to get the dimensions of the entire desktop via PyGtk. (After all, the deprecated function also still provides this.)


Solution

  • Based on the commit which removed those API calls, the algorithm that GDK uses to compute the screen size seems to be basically this:

    def get_screen_size(display):
        mon_geoms = [
            display.get_monitor(i).get_geometry()
            for i in range(display.get_n_monitors())
        ]
    
        x0 = min(r.x            for r in mon_geoms)
        y0 = min(r.y            for r in mon_geoms)
        x1 = max(r.x + r.width  for r in mon_geoms)
        y1 = max(r.y + r.height for r in mon_geoms)
    
        return x1 - x0, y1 - y0
    
    # example use
    print(get_screen_size(Gdk.Display.get_default()))