SoFunction
Updated on 2025-04-11

Summary of different methods for obtaining screen DPI values ​​in Python

In Python, there are many ways to get the DPI of the screen (dots per inch). Here are a few common methods:

Method 1: Use the tkinter module

tkinter is a standard GUI library for Python, through which you can get the DPI of the screen.

import tkinter as tk

def get_screen_dpi():
    root = ()
    dpi_x = root.winfo_fpixels('1i')  # Get horizontal DPI    dpi_y = root.winfo_fpixels('1i')  # Get the vertical DPI    ()
    return dpi_x, dpi_y

dpi_x, dpi_y = get_screen_dpi()
print(f"Horizontal DPI: {dpi_x}")
print(f"Vertical DPI: {dpi_y}")

Method 2: Use screeninfo library

screeninfo is a third-party library that can get detailed information about the screen, including DPI. If it has not been installed, you can install it through the following command:

pip install screeninfo

Then use the following code to get the DPI:

from screeninfo import get_monitors

def get_screen_dpi():
    monitor = get_monitors()[0]  # Get information about the first monitor    width_mm = monitor.width_mm
    height_mm = monitor.height_mm
    width_px = 
    height_px = 

    # Calculate horizontal and vertical DPI    dpi_x = (width_px / width_mm) * 25.4
    dpi_y = (height_px / height_mm) * 25.4
    return dpi_x, dpi_y

dpi_x, dpi_y = get_screen_dpi()
print(f"Horizontal DPI: {dpi_x}")
print(f"Vertical DPI: {dpi_y}")

Method 3: Use win32api (Windows only)

If you are using a Windows system, you can use the pywin32 library to obtain DPI. If it has not been installed, you can install it through the following command:

pip install pywin32

Then use the following code:

import win32api
import win32print

def get_screen_dpi():
    hdc = (0)
    dpi_x = (hdc, )
    dpi_y = (hdc, )
    (hdc)
    return dpi_x, dpi_y

dpi_x, dpi_y = get_screen_dpi()
print(f"Horizontal DPI: {dpi_x}")
print(f"Vertical DPI: {dpi_y}")

Method 4: Use matplotlib (for drawing scenes)

If you are drawing using matplotlib, you can get the screen DPI through the Figure object of matplotlib:

import  as plt

def get_screen_dpi():
    fig = ()
    dpi = 
    (fig)
    return dpi

dpi = get_screen_dpi()
print(f"Screen DPI: {dpi}")

Summarize

If you only need a simple solution, tkinter is a good choice.

If you need more detailed screen information, screeninfo is a powerful tool.

If you are using a Windows system, win32api can provide more underlying access.

If you are using matplotlib, you can directly take advantage of its functionality.

Just choose the right method according to your specific needs.

This is the end of this article about the different methods of obtaining screen DPI values ​​in Python. For more related content on obtaining screen DPI values ​​in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!