How to get monitor resolution in Python?

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

+93
python screen resolution
Jun 27 '10 at 23:39
source share
27 answers

On Windows:

from win32api import GetSystemMetrics print("Width =", GetSystemMetrics(0)) print("Height =", GetSystemMetrics(1)) 

If you are working with a high-resolution screen, make sure your Python interpreter has HIGHDPIAWARE.

Based on this post.

+56
Jun 27 '10 at 23:41
source share
β€” -

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

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

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

For installations with multiple monitors, you can get the combined width and height of the virtual monitor:

 import ctypes user32 = ctypes.windll.user32 screensize = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79) 
+103
Jun 28 2018-10-06T00:
source share

I created the 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(1920x1080+1920+0) monitor(1920x1080+0+0) 

It supports multi-monitor environments . His goal is to be cross-platform; it currently supports Cygwin and X11, but pull requests are welcome.

+68
Jul 01 '15 at 20:50
source share

If you use wxWindows, you can simply:

 import wx app = wx.App(False) # the wx.App object must be created first. print(wx.GetDisplaySize()) # returns a tuple 
+43
Jun 28 2018-10-06T00:
source share

Taken directly from the answer to this post: How to get the screen size in Tkinter?

 import tkinter as tk root = tk.Tk() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() 
+39
May 13 '13 at 19:29
source share

On Windows 8.1 I do not get the correct permission from ctypes or tk. Other people have the same problem for ctypes: getsystemmetrics returns the wrong screen size. To get the correct full resolution of a high DPI monitor in Windows 8.1, you need to 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 reports scaled resolution. Python seems to be the default dpi-enabled application. DPI types of applications are listed here: http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor

In fact, instead of displaying content with full monitor resolution, which can lead to a decrease in font sizes, the content is scaled until the fonts are large enough.

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

For this Windows site: http://msdn.microsoft.com/en-us/library/aa770067%28v=vs.85%29.aspx The formula for effectively resolving the reported system is: (reports_px * current_dpi) / (96 dpi)) = Physical_px

I can get the correct screen resolution and current DPI with the code below. Note that I call SetProcessDPIAware () so that the program can 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 is back:

 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 using Windows 8.1 with a monitor with a resolution of 220 dpi. My screen scaling sets my current DPI to 158.

I will use 158 to make sure my Matplotlib plots are the right size with: from pylab import rcParams rcParams ['figure.dpi'] = curr_dpi

+23
Oct 23 '14 at 23:20
source share

And for completeness, Mac OS X

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

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

+16
Jun 28 2018-10-10T00:
source share

If you use the Qt Qt 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() 
+14
Jul 04 '13 at 16:42
source share

Using Linux, the easiest way is to run the bash command

 xrandr | grep '*' 

and analyze its output using regexp.

You can also do this through PyGame: http://www.daniweb.com/forums/thread54881.html

+12
Jun 27 '10 at 23:53 on
source share

Here is a small little Python program that displays information about your setup of multiple monitors:

 import gtk window = gtk.Window() # the screen contains all monitors screen = window.get_screen() print "screen size: %dx %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: %dx %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: %dx %d (current)" % (curmon,width,height) 

Here is 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) 
+12
May 12 '14 at 11:39
source share

I use the get_screen_resolution method in one of my projects like the one below, which is basically an import chain. You can change this according to your needs by deleting those parts that are not needed and move the more likely ports up 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) 
+9
Jan 19 '14 at 4:18
source share

An old question, but that’s not enough. I am new to Python, so please tell me if this is a "bad" solution. This solution is supported only for Windows and MacOS and works only for the main screen - but the OS is not mentioned in this question.

Measure the size by taking a screenshot. Since the screen size should not change, this should be done only once. There are more elegant solutions if you have installed graphical tools such as GTK, wx, ....

see the pillow

 pip install Pillow 



 from PIL import ImageGrab img = ImageGrab.grab() print (img.size) 
+7
Mar 21 '17 at 10:13
source share

XWindows 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) 
+6
Apr 22 '13 at 3:24
source share

If 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)) 
+5
Aug 04 '15 at 20:43
source share

Try using the following code:

 import subprocess resuls = subprocess.Popen(['xrandr'],stdout=subprocess.PIPE).communicate()[0].split("current")[1].split(",")[0] width = resuls.split("x")[0].strip() heigth = resuls.split("x")[1].strip() print width + "x" + heigth 
+5
Oct 12 '15 at 14:26
source share

Using Linux Instead of regexp, take the first line and take out the current resolution values.

Current display resolution: 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 %sx %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 from other versions, but this should be easy to understand.

+3
Jan 02 '13 at 15:04
source share

Answer extension @ user2366975 to get the current screen size in multiscreen 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 only on Linux)

+3
Jul 06 '19 at 9:56
source share

To get a bit 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)) 

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
Jun 19 '14 at 15:26
source share

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) 
+2
Aug 02 '17 at 18:03
source share

Using pygame :

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

[one]

However, if you are trying to adjust the window to screen size, you can simply do:

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

to adjust the display in full screen. [2]

+2
09 Oct '17 at 18:27
source share

Try pyautogui:

 import pyautogui resolution = pyautogui.size() print(resolution) 
+1
Aug 15 '16 at 20:38
source share

If you are running Windows, you can use the 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

+1
May 28 '19 at 6:37
source share

A cross-platform and easy way to do this is to use TKinter, which comes with almost all versions of Python, so you don't need to install anything:

 import tkinter root = tkinter.Tk() root.withdraw() WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight() 
+1
Jul 20 '19 at 13:49
source share

You can use PyMouse . To get the screen size, just use screen_size() :

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

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

Link to the function in the documentation.

0
Apr 15 '18 at 14:16
source share

On Linux we can use the 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()) 
0
Sep 28 '18 at 7:43
source share

This is a bit troublesome for the retina screen, I use tkinter to get a fake size, use pilllow grab to get the 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 
0
Apr 25 '19 at 10:11
source share

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: %dx %d" % (m, geometry.width, geometry.height)) 
0
Aug 17 '19 at 12:29
source share



All Articles