How do I get monitor resolution in Python?

后端 未结 30 1086
深忆病人
深忆病人 2020-11-22 13:49

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

相关标签:
30条回答
  • 2020-11-22 14:26

    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)
    
    0 讨论(0)
  • 2020-11-22 14:26

    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,
    
    0 讨论(0)
  • 2020-11-22 14:26

    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
    
    0 讨论(0)
  • 2020-11-22 14:28

    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)
    
    0 讨论(0)
  • 2020-11-22 14:29

    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)
    
    0 讨论(0)
  • 2020-11-22 14:29

    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)
    
    0 讨论(0)
提交回复
热议问题