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()结果是一样的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)