Search code examples
pythontkinterctypespywin32screen-resolution

Getting Display resolution with python isn't accurate


In Settings > Display it says that my screen resolution is set to 1920x1080 enter image description here. But I've tried to get it with 3 different methods in python:

1- With Tkinter:

from tkinter import *
root = Tk()
Width = root.winfo_screenwidth()
Height= root.winfo_screenheight()

2- With win32api:

from win32api import GetSystemMetrics
Width = GetSystemMetrics(0)
Height = GetSystemMetrics(1)

3- With ctypes:

import ctypes
Width = ctypes.windll.user32.GetSystemMetrics(0)
Height = ctypes.windll.user32.GetSystemMetrics(1)

All of these methods keep returning Width = 1536 and Height = 864 and not the resolution that it says in my display settings.

How could I get the same resolution as displayed in the Display Settings (1920x1080)?


Solution

  • This problem is caused by the scaling setting that is set to 125%.

    So I found 2 solutions:

    The First one answered by @spacether in @rectangletangle's question:

    import ctypes
    user32 = ctypes.windll.user32
    user32.SetProcessDPIAware()
    Width = user32.GetSystemMetrics(0)
    Height = user32.GetSystemMetrics(1)
    

    The Second one:

    import win32con, win32gui, win32print
    def get_dpi():
      hDC = win32gui.GetDC(0)
      HORZRES = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)
      VERTRES = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)
      return HORZRES,VERTRES