Wednesday, February 18, 2015

Get Screen Dimensions in Python

Here's how to get your screen size in pixels on a number of different toolkits and operating systems in Python. Some methods are limited to only the default monitor, but others can provide a list of (width, height) tuples of all monitors in use.

Using Tkinter (recommended)

No PyPI packages required, and is cross platform.
from tkinter import Tk
root = Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()

Using wxPython

wxWidgets is available for many platforms.
Required package for Python2: wxPython
Required package for Python3: wxPython-Phoenix (currently not on PyPI)
import wx
wx.App(False)  # A wx.App must be created first.
width, height = wx.GetDisplaySize().Get()

Using PyGLet

Required PyPI package: pyglet
from pyglet.window import Platform
screen = Platform().get_default_display().get_default_screen()
width, height = screen.width, screen.height

Using PyGObject on GNOME

Pre-installed on Ubuntu and possibly other Linux distros too.
Required PyPI package: PyGObject
Single Monitor using GTK
from gi.repository.Gtk import Window
screen = Window().get_screen()
width, height = screen.width(), screen.height()
Single Monitor using GDK
from gi.repository.Gdk import Screen
screen = Screen.get_default()
width, height = screen.width(), screen.height()
Multi-Monitor
from gi.repository.Gtk import Window
screen = Window().get_screen()
screens = [(s.width, s.height) for s in [
    screen.get_monitor_geometry(x) for x in
        range(screen.get_n_monitors())]]
Returns a list of (width, height) tuples for each screen.

Using Xlib on X Server

Required PyPI package for Python3: python3-xlib
Single Monitor
from Xlib.display import Display
screen = Display().screen().root.get_geometry()
width, height = screen.width, screen.height
Multi-Monitor
from Xlib.display import Display
screens = [(r.width_in_pixels, r.height_in_pixels)
    for r in Display().display.info.roots]
Returns a list of (width, height) tuples for each screen.

Using ctypes on Windows

No PyPI packages required, and works on WINE.
from ctypes.windll.user32 import GetSystemMetrics
width, height = GetSystemMetrics(0), GetSystemMetrics(1)

Using pywin32 on Windows

Required PyPI packages: pywin32
from win32api import GetSystemMetrics
width, height = GetSystemMetrics(0), GetSystemMetrics(1) 

Using AppKit on Mac OS X

from AppKit import NSScreen
screens = [(s.frame().size.width, s.frame().size.height)
    for s in NSScreen.screens()]
Returns a list of (width, height) tuples for each screen.

1 comment :

  1. Great Collection. I'm currently doing the same googling you must have done. I could have a lot of time coming here first!

    ReplyDelete