python学习杂记——获取屏幕分辨率的三种方法

一、利用thinter库

import tkinter as tk 

root = tk.Tk() print(root.winfo_screenwidth()) print(root.winfo_screenheight()) root.destroy()

 标准库不用pip install

这段代码的运行测试:

E:\py>python tp2.py 1920 1080

 

二、利用ctypes库

import ctypes

user32 = ctypes.windll.user32

#单显示器屏幕宽度和高度:
screen_size0 = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
#对于多显示器设置,您可以检索虚拟显示器的组合宽度和高度:
screen_size1 = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)

print(screen_size0," ", screen_size1)

标准库不用pip install,实测两个显示器扩展显示结果是正确的。

三、利用pywin32库 

from win32.lib import win32con
from win32 import win32api, win32gui, win32print
 
###获取真实的分辨率
def get_real_screen_resolution():
    hDC = win32gui.GetDC(0)
    width = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)
    height = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)
    return {"width": width, "height": height}
 
###获取缩放后的分辨率
def get_screen_size():
    width = win32api.GetSystemMetrics(0)
    height = win32api.GetSystemMetrics(1)
    return {"width": width, "height": height}
 
###获取屏幕的缩放比例
def get_screen_scale():
    real_resolution = get_real_screen_resolution()
    screen_size = get_screen_size()
    proportion = round(real_resolution['width'] / screen_size['width'], 2)
    return proportion

print("屏幕真实分辨率:",get_real_screen_resolution()["width"], 'x', get_real_screen_resolution()["height"])
print("缩放后的屏幕分辨率:",get_screen_size()["width"], 'x', get_screen_size()["height"])
print("屏幕缩放比:",get_screen_scale())

需要pip install pywin32。实测win10/11即使使用屏幕缩放,其分辨是不变的,所以get_screen_size()和get_real_screen_resolution()结果是一样的。

 

 

posted @ 2022-06-13 10:08  遇事修性遇人修心  阅读(3302)  评论(0编辑  收藏  举报