194

What is the simplest way to get monitor resolution (preferably in a tuple)?

nbro
  • 15,395
  • 32
  • 113
  • 196
rectangletangle
  • 50,393
  • 94
  • 205
  • 275
  • Are you using a particular UI toolkit? (eg. GTK, wxPython, Tkinter, etc) – detly Jun 28 '10 at 02:25
  • 14
    With the `Tkinter` module, you can do it [this way](http://stackoverflow.com/questions/3949844/python-calculate-the-screen-size/3949983#3949983). It's part of the standard Python library and works on most Unix and Windows platforms. – martineau Oct 17 '10 at 19:44
  • 1
    A good overview over different techniques for common UIs is given at [this link](https://www.blog.pythonlibrary.org/2015/08/18/getting-your-screen-resolution-with-python/) – ImportanceOfBeingErnest May 21 '17 at 18:41

33 Answers33

186

I created a PyPI module for this reason:

pip install screeninfo

The code:

from screeninfo import get_monitors
for m in get_monitors():
    print(str(m))

Result:

Monitor(x=3840, y=0, width=3840, height=2160, width_mm=1420, height_mm=800, name='HDMI-0', is_primary=False)
Monitor(x=0, y=0, width=3840, height=2160, width_mm=708, height_mm=399, name='DP-0', is_primary=True)

It supports multi monitor environments. Its goal is to be cross platform; for now it supports Cygwin and X11 but pull requests are totally welcome.

Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
rr-
  • 14,303
  • 6
  • 45
  • 67
  • 4
    Works great on Windows but Mac I get the following Error: ImportError: Could not load X11 – Chris Lucian Jan 15 '16 at 05:11
  • 7
    Works great on Ubuntu. Tested on Ubuntu 16.04. – Dhruv Reshamwala Sep 20 '16 at 06:21
  • 5
    FYI, Windows DPI scaling still applies. This line will tell Windows you want the raw, unscaled resolution: "import ctypes; user32 = ctypes.windll.user32; user32.SetProcessDPIAware()". 1) Your answer should be top; good job. 2) My comment is Windows-specific, not library specific (i.e. screeninfo) 3) code ripped and tested from KobeJohn's comment here: https://stackoverflow.com/a/32541666/2616321 – Jason2616321 Jul 17 '17 at 17:28
  • 8
    Handy module (+1). I had to install a couple of requirements (e.g. `pip install cython pyobjus`) before I could use it on OSX though – George Profenza Mar 08 '19 at 03:13
  • Good module. Works properly with 4k resolution on Windows 10. – BadLagger Jan 24 '22 at 19:39
  • Can you add `is_mobile` etc functions ? – Ricky Levi Jul 20 '22 at 17:04
154

In Windows, you can also use ctypes with GetSystemMetrics():

import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)

so that you don't need to install the pywin32 package; it doesn't need anything that doesn't come with Python itself.

For multi-monitor setups, you can retrieve the combined width and height of the virtual monitor:

import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)
Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
jcao219
  • 2,808
  • 3
  • 21
  • 22
  • 17
    Important note: the values returned may be incorrect if DPI scaling is used (ie: often the case on 4k displays), you have to call SetProcessDPIAware before initializing the GUI components (and not before calling the GetSystemMetrics function). This is true for most of the answers here (GTK, etc) on the win32 platform. – totaam Sep 29 '14 at 04:09
  • 2
    For multiple monitors, you may use GetSystemMetrics(78) and GetSystemMetrics(79) – Derek Jul 20 '18 at 18:00
  • @Derek What does `GetSystemMetrics(78)` and `GetSystemMetrics(79)` return? – Stevoisiak Jul 30 '18 at 15:12
  • @StevenVascellaro The width/height of the virtual screen, in pixels. https://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx – Derek Jul 30 '18 at 20:42
103

On Windows:

from win32api import GetSystemMetrics

print("Width =", GetSystemMetrics(0))
print("Height =", GetSystemMetrics(1))

If you are working with high resolution screen, make sure your python interpreter is HIGHDPIAWARE.

Based on this post.

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
Robus
  • 8,067
  • 5
  • 47
  • 67
63

Taken directly from an answer to the post How can I get the screen size in Tkinter?,

import tkinter as tk

root = tk.Tk()

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2366975
  • 4,350
  • 9
  • 47
  • 87
  • 12
    If you have external displays extended to beside the primary display, this method would give the sum of all displays resolutions, not the current display resolution. – jadelord Jul 25 '16 at 10:08
  • For a multiple screen step see [my answer](https://stackoverflow.com/a/56913005/5218354). – norok2 Jul 06 '19 at 10:00
  • I strongly suggest against using tkinter. I wasted a lot of time to realize that if you set your screen resolution to a certain value in windows, but if the text size (as set in Display setting in Windows) is not set to 100%, then value you get from tkinter is scaled by the font size. AS an example, a resolutoin of (3829, 2160), with a text size of 250% will be reported as (1536, 86). – Vahid S. Bokharaie Feb 09 '23 at 09:50
48

If you're using wxWindows (having installed wxPython), you can simply do:

import wx

app = wx.App(False) # the wx.App object must be created first.    
print(wx.GetDisplaySize())  # returns a tuple
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • This is the best one... who don't have wx? :) plus a few lines instead a bunch of code on your eyes. This is now my default method, thank you. – m3nda Oct 26 '15 at 11:59
  • 1
    This should be `app = wx.App(False)` otherwise you get the "the wx.App object must be created first." error. 26 votes and no one did check? Does work in Windows without assing wx instance to a variable? – m3nda Oct 26 '15 at 12:23
  • 5
    Who don't have wx? Many people? – marsh Sep 16 '16 at 13:40
41

On Windows 8.1 I am not getting the correct resolution from either ctypes or tk. Other people are having this same problem for ctypes: getsystemmetrics returns wrong screen size

To get the correct full resolution of a high DPI monitor on Windows 8.1, one must call SetProcessDPIAware and use the following code:

import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]

Full Details Below:

I found out that this is because windows is reporting a scaled resolution. It appears that python is by default a 'system dpi aware' application. Types of DPI aware applications are listed here: High DPI Desktop Application Development on Windows

Basically, rather than displaying content the full monitor resolution, which would make fonts tiny, the content is scaled up until the fonts are big enough.

On my monitor I get:
Physical resolution: 2560 x 1440 (220 DPI)
Reported python resolution: 1555 x 875 (158 DPI)

Per this Windows site: Adjusting Scale for Higher DPI Screens. The formula for reported system effective resolution is:

(reported_px*current_dpi)/(96 dpi) = physical_px

I'm able to get the correct full screen resolution, and current DPI with the below code. Note that I call SetProcessDPIAware() to allow the program to see the real resolution.

import tkinter as tk
root = tk.Tk()

width_px = root.winfo_screenwidth()
height_px = root.winfo_screenheight()
width_mm = root.winfo_screenmmwidth()
height_mm = root.winfo_screenmmheight()
# 2.54 cm = in
width_in = width_mm / 25.4
height_in = height_mm / 25.4
width_dpi = width_px/width_in
height_dpi = height_px/height_in

print('Width: %i px, Height: %i px' % (width_px, height_px))
print('Width: %i mm, Height: %i mm' % (width_mm, height_mm))
print('Width: %f in, Height: %f in' % (width_in, height_in))
print('Width: %f dpi, Height: %f dpi' % (width_dpi, height_dpi))

import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
print('Size is %f %f' % (w, h))

curr_dpi = w*96/width_px
print('Current DPI is %f' % (curr_dpi))

Which returned:

Width: 1555 px, Height: 875 px
Width: 411 mm, Height: 232 mm
Width: 16.181102 in, Height: 9.133858 in
Width: 96.099757 dpi, Height: 95.797414 dpi
Size is 2560.000000 1440.000000
Current DPI is 158.045016

I am running Windows 8.1 with a 220 DPI capable monitor. My display scaling sets my current DPI to 158.

I'll use the 158 to make sure my Matplotlib plots are the right size with:

from pylab import rcParams
rcParams['figure.dpi'] = curr_dpi
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
spacether
  • 2,136
  • 1
  • 21
  • 28
  • 1
    You have a lot of good information here, but the answer itself is buried in the middle. To make it a bit easier to read, can you clarify exactly what the answer is and *then* provide the background information? – skrrgwasme Oct 23 '14 at 23:49
  • I edited my post to show the answer in the beginning, then get into the details. Thanks for the feedback. – spacether Oct 24 '14 at 04:49
  • 2
    It looks like there is a flaw in the calculations here, which is easy to spot it you calculate a diagonal size from the reported width and height (in inches). My screen with 13.3 inches diagonal was reported as 15 inch. It seems `Tkinter` is using correct pixels, but is not aware of the dpi scaling thus reporting wrong mm sizes. – Primer Apr 02 '15 at 09:35
  • This doesn't work on Windows 10, there the SetSystemDPIAware() doesn't seem to make a difference. However, calling ctypes.windll.shcore.SetProcessDpiAwareness(2) instead seems to do the trick. – Klamer Schutte Sep 22 '17 at 07:35
  • @KlamerSchutte: `ctypes.windll.shcore.SetProcessDpiAwareness(2)` returns error `OSError: [WinError 126] The specified module could not be found`. – Adrian Keister Oct 03 '18 at 17:27
  • I'm in Win 7, though. – Adrian Keister Oct 03 '18 at 17:34
  • @spacether: This code does not seem to work in Windows 7, 64-bit. I'm getting a window width and window height that are way off. The `winfo_screenmmwidth()` function yields incorrect results. Any ideas? – Adrian Keister Oct 03 '18 at 18:05
  • @AdrianKeister if I were you I would try the other input_value to: user32.GetSystemMetrics(input_value) The possible values are listed here: https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getsystemmetrics and dig into what your current reported results are from wx, what they are from user32, what the difference is, and if that difference is from a DPI issue. – spacether Oct 03 '18 at 19:45
  • @spacether: Thanks! I'll try that and get back to you. – Adrian Keister Oct 03 '18 at 20:08
  • @spacether: I looked through the MS documentation to which you linked. Unfortunately, there are no methods for finding dpi or any conversion rate. Everything is in pixels. According to the specs on my monitor, it looks like it's returning the right number of pixels. But the density is definitely higher than 96 dpi, as I don't have a 20" wide monitor. user32 is returning numbers very close to what tkinter is. – Adrian Keister Oct 05 '18 at 18:46
  • @AdrianKeister in those docs it lists how those methods aren't dpi aware. A search for DPI in those docs shows that you should look into https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getsystemmetricsfordpi and https://learn.microsoft.com/en-us/windows/desktop/hidpi/high-dpi-desktop-application-development-on-windows – spacether Oct 09 '18 at 17:10
  • @spacether: Great, thanks! I'll check that out once I'm back with my Windows machine. Right now, I've got an experimental work-around, where I physically measured my monitor and got an empirical dpi. It's working pretty well, but this would obviously be more elegant if I could get it to work. – Adrian Keister Oct 09 '18 at 18:15
23

And for completeness, Mac OS X

import AppKit
[(screen.frame().size.width, screen.frame().size.height)
    for screen in AppKit.NSScreen.screens()]

will give you a list of tuples containing all screen sizes (if multiple monitors present)

cobbal
  • 69,903
  • 20
  • 143
  • 156
20

A cross-platform and easy way to do this is by using Tkinter that comes with nearly all the Python versions, so you don't have to install anything:

import tkinter
root = tkinter.Tk()
root.withdraw()
WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kitsiosk
  • 1,272
  • 9
  • 15
17

If you are using the Qt toolkit, specifically PySide, you can do the following:

from PySide import QtGui
import sys

app = QtGui.QApplication(sys.argv)
screen_rect = app.desktop().screenGeometry()
width, height = screen_rect.width(), screen_rect.height()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MadeOfAir
  • 2,933
  • 5
  • 31
  • 39
17

Old question but this is missing. I'm new to python so please tell me if this is a "bad" solution. This solution is supported for Windows and MacOS only and it works just for the main screen - but the os is not mentioned in the question.

Measure the size by taking a screenshot. As the screensize should not change this has to be done only once. There are more elegant solutions if you have a gui toolkit like GTK, wx, ... installed.

see Pillow

pip install Pillow

from PIL import ImageGrab

img = ImageGrab.grab()
print (img.size)
Nuno André
  • 4,739
  • 1
  • 33
  • 46
lumos0815
  • 3,908
  • 2
  • 25
  • 25
14

Expanding on @user2366975's answer, to get the current screen size in a multi-screen setup using Tkinter (code in Python 2/3):

try:
    # for Python 3
    import tkinter as tk
except ImportError:
    # for Python 2
    import Tkinter as tk


def get_curr_screen_geometry():
    """
    Workaround to get the size of the current screen in a multi-screen setup.

    Returns:
        geometry (str): The standard Tk geometry string.
            [width]x[height]+[left]+[top]
    """
    root = tk.Tk()
    root.update_idletasks()
    root.attributes('-fullscreen', True)
    root.state('iconic')
    geometry = root.winfo_geometry()
    root.destroy()
    return geometry

(Should work cross-platform, tested on Linux only)

norok2
  • 25,683
  • 4
  • 73
  • 99
  • 3
    Works great for me. If you make the fullscreen attribute False again and set the state to 'normal', you can re-use the new window created. – toxicantidote Nov 19 '20 at 23:05
13

Using Linux, the simplest way is to execute Bash command

xrandr | grep '*'

And parse its output using a regular expression.

Also you can do it through Pygame: Pygame - Get screen size

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
12

I am using a get_screen_resolution method in one of my projects like the one below, which is basically an import chain. You can modify this according to Your needs by removing those parts that are not needed and move more likely ports upwards in the chain.

PYTHON_V3 = sys.version_info >= (3,0,0) and sys.version_info < (4,0,0):
#[...]
    def get_screen_resolution(self, measurement="px"):
        """
        Tries to detect the screen resolution from the system.
        @param measurement: The measurement to describe the screen resolution in. Can be either 'px', 'inch' or 'mm'. 
        @return: (screen_width,screen_height) where screen_width and screen_height are int types according to measurement.
        """
        mm_per_inch = 25.4
        px_per_inch =  72.0 #most common
        try: # Platforms supported by GTK3, Fx Linux/BSD
            from gi.repository import Gdk 
            screen = Gdk.Screen.get_default()
            if measurement=="px":
                width = screen.get_width()
                height = screen.get_height()
            elif measurement=="inch":
                width = screen.get_width_mm()/mm_per_inch
                height = screen.get_height_mm()/mm_per_inch
            elif measurement=="mm":
                width = screen.get_width_mm()
                height = screen.get_height_mm()
            else:
                raise NotImplementedError("Handling %s is not implemented." % measurement)
            return (width,height)
        except:
            try: #Probably the most OS independent way
                if PYTHON_V3: 
                    import tkinter 
                else:
                    import Tkinter as tkinter
                root = tkinter.Tk()
                if measurement=="px":
                    width = root.winfo_screenwidth()
                    height = root.winfo_screenheight()
                elif measurement=="inch":
                    width = root.winfo_screenmmwidth()/mm_per_inch
                    height = root.winfo_screenmmheight()/mm_per_inch
                elif measurement=="mm":
                    width = root.winfo_screenmmwidth()
                    height = root.winfo_screenmmheight()
                else:
                    raise NotImplementedError("Handling %s is not implemented." % measurement)
                return (width,height)
            except:
                try: #Windows only
                    from win32api import GetSystemMetrics 
                    width_px = GetSystemMetrics (0)
                    height_px = GetSystemMetrics (1)
                    if measurement=="px":
                        return (width_px,height_px)
                    elif measurement=="inch":
                        return (width_px/px_per_inch,height_px/px_per_inch)
                    elif measurement=="mm":
                        return (width_px/mm_per_inch,height_px/mm_per_inch)
                    else:
                        raise NotImplementedError("Handling %s is not implemented." % measurement)
                except:
                    try: # Windows only
                        import ctypes
                        user32 = ctypes.windll.user32
                        width_px = user32.GetSystemMetrics(0)
                        height_px = user32.GetSystemMetrics(1)
                        if measurement=="px":
                            return (width_px,height_px)
                        elif measurement=="inch":
                            return (width_px/px_per_inch,height_px/px_per_inch)
                        elif measurement=="mm":
                            return (width_px/mm_per_inch,height_px/mm_per_inch)
                        else:
                            raise NotImplementedError("Handling %s is not implemented." % measurement)
                    except:
                        try: # Mac OS X only
                            import AppKit 
                            for screen in AppKit.NSScreen.screens():
                                width_px = screen.frame().size.width
                                height_px = screen.frame().size.height
                                if measurement=="px":
                                    return (width_px,height_px)
                                elif measurement=="inch":
                                    return (width_px/px_per_inch,height_px/px_per_inch)
                                elif measurement=="mm":
                                    return (width_px/mm_per_inch,height_px/mm_per_inch)
                                else:
                                    raise NotImplementedError("Handling %s is not implemented." % measurement)
                        except: 
                            try: # Linux/Unix
                                import Xlib.display
                                resolution = Xlib.display.Display().screen().root.get_geometry()
                                width_px = resolution.width
                                height_px = resolution.height
                                if measurement=="px":
                                    return (width_px,height_px)
                                elif measurement=="inch":
                                    return (width_px/px_per_inch,height_px/px_per_inch)
                                elif measurement=="mm":
                                    return (width_px/mm_per_inch,height_px/mm_per_inch)
                                else:
                                    raise NotImplementedError("Handling %s is not implemented." % measurement)
                            except:
                                try: # Linux/Unix
                                    if not self.is_in_path("xrandr"):
                                        raise ImportError("Cannot read the output of xrandr, if any.")
                                    else:
                                        args = ["xrandr", "-q", "-d", ":0"]
                                        proc = subprocess.Popen(args,stdout=subprocess.PIPE)
                                        for line in iter(proc.stdout.readline,''):
                                            if isinstance(line, bytes):
                                                line = line.decode("utf-8")
                                            if "Screen" in line:
                                                width_px = int(line.split()[7])
                                                height_px = int(line.split()[9][:-1])
                                                if measurement=="px":
                                                    return (width_px,height_px)
                                                elif measurement=="inch":
                                                    return (width_px/px_per_inch,height_px/px_per_inch)
                                                elif measurement=="mm":
                                                    return (width_px/mm_per_inch,height_px/mm_per_inch)
                                                else:
                                                    raise NotImplementedError("Handling %s is not implemented." % measurement)
                                except:
                                    # Failover
                                    screensize = 1366, 768
                                    sys.stderr.write("WARNING: Failed to detect screen size. Falling back to %sx%s" % screensize)
                                    if measurement=="px":
                                        return screensize
                                    elif measurement=="inch":
                                        return (screensize[0]/px_per_inch,screensize[1]/px_per_inch)
                                    elif measurement=="mm":
                                        return (screensize[0]/mm_per_inch,screensize[1]/mm_per_inch)
                                    else:
                                        raise NotImplementedError("Handling %s is not implemented." % measurement)
Martin Hansen
  • 597
  • 6
  • 5
12

Here is a quick little Python program that will display the information about your multi-monitor setup:

import gtk

window = gtk.Window()

# the screen contains all monitors
screen = window.get_screen()
print "screen size: %d x %d" % (gtk.gdk.screen_width(),gtk.gdk.screen_height())

# collect data about each monitor
monitors = []
nmons = screen.get_n_monitors()
print "there are %d monitors" % nmons
for m in range(nmons):
  mg = screen.get_monitor_geometry(m)
  print "monitor %d: %d x %d" % (m,mg.width,mg.height)
  monitors.append(mg)

# current monitor
curmon = screen.get_monitor_at_window(screen.get_active_window())
x, y, width, height = monitors[curmon]
print "monitor %d: %d x %d (current)" % (curmon,width,height)  

Here's an example of its output:

screen size: 5120 x 1200
there are 3 monitors
monitor 0: 1600 x 1200
monitor 1: 1920 x 1200
monitor 2: 1600 x 1200
monitor 1: 1920 x 1200 (current)
starfry
  • 9,273
  • 7
  • 66
  • 96
  • Does `gtk.Window()` get the `gdk_default_root_window`? Is that how you are certain `.get_screen` contains all monitors? – yatg Jul 17 '15 at 00:15
  • I ask because in my code Im trying to replicate your code, i am doing it in jsctypes, and it keeps telling me 0 monitors: https://gist.github.com/yajd/55441c9c3d0711ee4a38#file-gistfile1-txt-L3 – yatg Jul 17 '15 at 01:19
  • 2
    It's a while since I wrote that code but, if I recall correctly, what `gtk.Window()` does is create a new window (see [here](http://www.pygtk.org/docs/pygtk/class-gtkwindow.html)). The window's just a way to use `get_screen` to get the monitor information. It returns the screen that the window is on (or would be, if it were ever displayed). I guess it depends on the X configuration whether that "screen" contains all "monitors". It does on my system with Twinview. – starfry Jul 17 '15 at 10:43
  • Thanks @starfry! I needed to find a cross solution which gets all monitors and their dimensions regardless of screens. Have you had any chacne to develop something like that? :) – yatg Jul 17 '15 at 17:30
  • Alternative for later toolkit versions: ```python – satyagraha Aug 17 '19 at 12:27
9

X Window version:

#!/usr/bin/python

import Xlib
import Xlib.display

resolution = Xlib.display.Display().screen().root.get_geometry()
print str(resolution.width) + "x" + str(resolution.height)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cpoakes
  • 91
  • 1
  • 1
6

In case you have PyQt4 installed, try the following code:

from PyQt4 import QtGui
import sys

MyApp = QtGui.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))

For PyQt5, the following will work:

from PyQt5 import QtWidgets
import sys

MyApp = QtWidgets.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))
6

On Linux:

import subprocess
import re

def getScreenDimensions():
    xrandrOutput = str(subprocess.Popen(['xrandr'], stdout=subprocess.PIPE).communicate()[0])
    matchObj = re.findall(r'current\s(\d+) x (\d+)', xrandrOutput)
    if matchObj:
        return (int(matchObj[0][0]), int(matchObj[0][1]))

screenWidth, screenHeight = getScreenDimensions()
print(f'{screenWidth} x {screenHeight}')
Adamq
  • 29
  • 2
  • 7
Taghouti Tarek
  • 104
  • 1
  • 10
5

Try pyautogui:

import pyautogui
resolution = pyautogui.size()
print(resolution) 
Tyler
  • 67
  • 1
  • 1
  • You should really add some explanation as to why this code should work - you can also add comments in the code itself - in its current form, it does not provide any explanation which can help the rest of the community to understand what you did to solve/answer the question. But this is also a very old question - with an accepted answer... – ishmaelMakitla Aug 15 '16 at 20:45
4

If you are working on Windows OS, you can use OS module to get it:

import os
cmd = 'wmic desktopmonitor get screenheight, screenwidth'
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))

It will return a tuple (Y,X) where Y is the vertical size and X is the horizontal size. This code works on Python 2 and Python 3

UPDATE

For Windows 8/8.1/10, the above answer doesn't work, use the next one instead:

import os
cmd = "wmic path Win32_VideoController get CurrentVerticalResolution,CurrentHorizontalResolution"
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))
Diroallu
  • 824
  • 1
  • 11
  • 15
4

A lot of these answers use tkinter to find the screen height/width (resolution), but sometimes it is necessary to know the dpi of your screen cross-platform compatible. This answer is from this link and left as a comment on another post, but it took hours of searching to find. I have not had any issues with it yet, but please let me know if it does not work on your system!

import tkinter
root = tkinter.Tk()
dpi = root.winfo_fpixels('1i')

The documentation for this says:

winfo_fpixels(number)
# Return the number of pixels for the given distance NUMBER (e.g. "3c") as float

A distance number is a digit followed by a unit, so 3c means 3 centimeters, and the function gives the number of pixels on 3 centimeters of the screen (as found here). So to get dpi, we ask the function for the number of pixels in 1 inch of screen ("1i").

Andrew Pye
  • 558
  • 3
  • 16
3

Using Linux

Instead of a regular expression, take the first line and take out the current resolution values.

Current resolution of display :0

>>> screen = os.popen("xrandr -q -d :0").readlines()[0]
>>> print screen
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 1920 x 1920
>>> width = screen.split()[7]
>>> print width
1920
>>> height = screen.split()[9][:-1]
>>> print height
1080
>>> print "Current resolution is %s x %s" % (width,height)
Current resolution is 1920 x 1080

This was done on xrandr 1.3.5, I don't know if the output is different on other versions, but this should make it easy to figure out.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex R
  • 637
  • 1
  • 8
  • 20
  • sadly not very good with multimonitor setups. not python's fault, but using this may have unexpected results... – black_puppydog May 18 '13 at 20:38
  • *"Instead of a regular expression"* probably refers to [Pavel Strakhov's answer](https://stackoverflow.com/questions/3129322/how-do-i-get-monitor-resolution-in-python/3129369#3129369). – Peter Mortensen Oct 08 '21 at 09:50
3

Using pygame:

import pygame
pygame.init()
infos = pygame.display.Info()
screen_size = (infos.current_w, infos.current_h)

[1]

However, if you're trying to set your window to the size of the screen, you might just want to do:

pygame.display.set_mode((0,0),pygame.FULLSCREEN)

to set your display to fullscreen mode. [2]

Tom Burrows
  • 2,225
  • 2
  • 29
  • 46
3

Late to the game. I think I found the cross-platform using the dependence-free library mss that supports multiple monitors (https://pypi.org/project/mss/):

import mss
sct=mss.mss()
sct.monitors

Then you get something like this:

[{'left': -1440, 'top': 0, 'width': 4000, 'height': 1080},
 {'left': 0, 'top': 0, 'width': 2560, 'height': 1080},
 {'left': -1440, 'top': 180, 'width': 1440, 'height': 900}]

The element 0 is the virtual screen combining all monitors. The element 1 is the primary monitor, and element 2 the second monitor.

Jerry T
  • 1,541
  • 1
  • 19
  • 17
2

To get bits per pixel:

import ctypes
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32

screensize = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
print "screensize =%s"%(str(screensize))
dc = user32.GetDC(None);

screensize = (gdi32.GetDeviceCaps(dc,8), gdi32.GetDeviceCaps(dc,10), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
screensize = (gdi32.GetDeviceCaps(dc,118), gdi32.GetDeviceCaps(dc,117), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))

parameters in gdi32:

#/// Vertical height of entire desktop in pixels
#DESKTOPVERTRES = 117,
#/// Horizontal width of entire desktop in pixels
#DESKTOPHORZRES = 118,
#/// Horizontal width in pixels
#HORZRES = 8,
#/// Vertical height in pixels
#VERTRES = 10,
#/// Number of bits per pixel
#BITSPIXEL = 12,
2

Another version using xrandr:

import re
from subprocess import run, PIPE

output = run(['xrandr'], stdout=PIPE).stdout.decode()
result = re.search(r'current (\d+) x (\d+)', output)
width, height = map(int, result.groups()) if result else (800, 600)
sirex
  • 4,593
  • 2
  • 32
  • 21
1

You could use PyMouse. To get the screen size just use the screen_size() attribute:

from pymouse import PyMouse
m = PyMouse()
a = m.screen_size()

a will return a tuple, (X, Y), where X is the horizontal position and Y is the vertical position.

Link to function in documentation.

Xantium
  • 11,201
  • 10
  • 62
  • 89
1

For later versions of PyGtk:

import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk

display = Gdk.Display.get_default()
n_monitors = display.get_n_monitors()
print("there are %d monitors" % n_monitors)
for m in range(n_monitors):
  monitor = display.get_monitor(m)
  geometry = monitor.get_geometry()
  print("monitor %d: %d x %d" % (m, geometry.width, geometry.height))
satyagraha
  • 623
  • 7
  • 11
1

For Linux, you can use this:

import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk

s = Gdk.Screen.get_default()
screen_width = s.get_width()
screen_height = s.get_height()
print(screen_width)
print(screen_height)
jefflgaol
  • 73
  • 1
  • 5
  • An explanation would be in order. E.g., what is it based on on Linux? [GTK](https://en.wikipedia.org/wiki/GTK)? What is the minimum version requirements (packages, Python, etc)? Does it work out of the box on e.g. [Ubuntu 20.04](https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_20.04_LTS_(Focal_Fossa))? What needs to be installed, if any? On which system was this tested (incl. version information)? Please respond by [editing (changing) your answer](https://XXXX), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Oct 08 '21 at 10:05
0

On Linux we can use subprocess module

import subprocess
cmd = ['xrandr']
cmd2 = ['grep', '*']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p.stdout, stdout=subprocess.PIPE)
p.stdout.close()

resolution_string, junk = p2.communicate()
resolution = resolution_string.split()[0]
resolution = resolution.decode("utf-8") 
width = int(resolution.split("x")[0].strip())
heigth = int(resolution.split("x")[1].strip())
kamran kausar
  • 4,117
  • 1
  • 23
  • 17
0

It's a little troublesome for retina screen, i use tkinter to get the fake size, use pilllow grab to get real size :

import tkinter
root = tkinter.Tk()
resolution_width = root.winfo_screenwidth()
resolution_height = root.winfo_screenheight()
image = ImageGrab.grab()
real_width, real_height = image.width, image.height
ratio_width = real_width / resolution_width
ratio_height = real_height/ resolution_height
NicolasLi
  • 97
  • 1
  • 3
0

Utility script using pynput library. Posting here for ref.:

 
from pynput.mouse import Controller as MouseController

def get_screen_size():
    """Utility function to get screen resolution"""

    mouse = MouseController()

    width = height = 0

    def _reset_mouse_position():
        # Move the mouse to the top left of 
        # the screen
        mouse.position = (0, 0)

    # Reset mouse position
    _reset_mouse_position()

    count = 0
    while 1:
        count += 1
        mouse.move(count, 0)
        
        # Get the current position of the mouse
        left = mouse.position[0]

        # If the left doesn't change anymore, then
        # that's the screen resolution's width
        if width == left:
            # Add the last pixel
            width += 1

            # Reset count for use for height
            count = 0
            break

        # On each iteration, assign the left to 
        # the width
        width = left
    
    # Reset mouse position
    _reset_mouse_position()

    while 1:
        count += 1
        mouse.move(0, count)

        # Get the current position of the mouse
        right = mouse.position[1]

        # If the right doesn't change anymore, then
        # that's the screen resolution's height
        if height == right:
            # Add the last pixel
            height += 1
            break

        # On each iteration, assign the right to 
        # the height
        height = right

    return width, height

>>> get_screen_size()
(1920, 1080)
olumidesan
  • 111
  • 4
0

Try using pyautogui.size()!

import pyautogui #pip install pyautogui

x = pyautogui.size()[0] # getting the width of the screen
y = pyautogui.size()[1] # getting the height of the screen

print(x,y) 
ChucK
  • 2,114
  • 1
  • 18
  • 20
Capt.Pyrite
  • 851
  • 7
  • 24
0

Here is another one which hasn't been mentioned yet. Windows only - uses user32.EnumDisplayMonitors - Pure Python

def get_monitors_resolution():
    user32 = ctypes.windll.user32
    def _get_monitors_resolution():
        monitors = []
        monitor_enum_proc = ctypes.WINFUNCTYPE(
            ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.POINTER(ctypes.wintypes.RECT), ctypes.c_double)
        def callback(hMonitor, hdcMonitor, lprcMonitor, dwData):
            monitors.append((lprcMonitor.contents.right - lprcMonitor.contents.left,
                             lprcMonitor.contents.bottom - lprcMonitor.contents.top))
            return 1
        user32.EnumDisplayMonitors(None, None, monitor_enum_proc(callback), 0)
        return monitors
    resolutions = _get_monitors_resolution()
    allmonitors = {}
    for i, res in enumerate(resolutions):
        allmonitors[i] = {'width': res[0], 'height': res[1]}
    return allmonitors
get_monitors_resolution()
Out[2]: {0: {'width': 1920, 'height': 1080}, 1: {'width': 1920, 'height': 1080}}
Hans
  • 148
  • 2
  • 7