How do I get monitor resolution in Python?

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

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

30条回答
  •  遇见更好的自我
    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)
    

提交回复
热议问题