pywin32
方法一
使用 win32api.GetDeviceCaps() 方法來獲取顯示器的分辨率。
使用 win32api.GetDC() 方法獲取整個屏幕的設(shè)備上下文句柄,然后使用 win32api.GetDeviceCaps() 方法獲取水平和垂直方向的分辨率。最后需要調(diào)用 win32api.ReleaseDC() 方法釋放設(shè)備上下文句柄。
import win32api
import win32con
hdc = win32api.GetDC(0)
screen_width = win32api.GetDeviceCaps(hdc, win32con.HORZRES)
screen_height = win32api.GetDeviceCaps(hdc, win32con.VERTRES)
win32api.ReleaseDC(0, hdc)
print(f"屏幕分辨率為:{screen_width} x {screen_height}")
方法二
使用 win32api.EnumDisplayMonitors() 方法來枚舉所有顯示器并獲取其分辨率。
此方法返回一個列表,其中每個元素代表一個顯示器的矩形區(qū)域??梢詮木匦螀^(qū)域計算出顯示器的寬度和高度,從而確定其分辨率。
import win32api
import win32con
def get_monitor_info():
monitors = []
monitor_enum_proc = lambda hMonitor, hdcMonitor, lprcMonitor, dwData: monitors.append(lprcMonitor)
win32api.EnumDisplayMonitors(None, None, monitor_enum_proc, 0)
return monitors
monitors = get_monitor_info()
for i, monitor in enumerate(monitors):
width = monitor[2] - monitor[0]
height = monitor[3] - monitor[1]
print(f"第{i+1}個顯示器分辨率為:{width} x {height}")
方法三
import win32api
screen_width = win32api.GetSystemMetrics(0)
screen_height = win32api.GetSystemMetrics(1)
print(f"屏幕分辨率為:{screen_width} x {screen_height}")
Pillow
需要注意的是,此方法需要安裝 Pillow 模塊??梢酝ㄟ^運行 pip install Pillow
命令來安裝。使用 ImageGrab 模塊的 grab() 方法來獲取整個屏幕的截圖,然后從截圖中讀取寬度和高度以獲取屏幕分辨率。
from PIL import ImageGrab
screen = ImageGrab.grab()
screen_width, screen_height = screen.size
print(f"屏幕分辨率為:{screen_width} x {screen_height}")
ctypes
需要注意的是,此方法僅適用于 Windows 操作系統(tǒng),并且并未安裝任何第三方庫。通過調(diào)用 Windows 用戶界面庫中的 GetSystemMetrics 函數(shù)來獲取屏幕分辨率。
import ctypes
user32 = ctypes.windll.user32
screen_width = user32.GetSystemMetrics(0)
screen_height = user32.GetSystemMetrics(1)
print(f"屏幕分辨率為:{screen_width} x {screen_height}")
pygetwindow
import pygetwindow as gw
screen = gw.getWindowsWithTitle('')[0]
screen_width, screen_height = screen.size
print(f"屏幕分辨率為:{screen_width} x {screen_height}")
運行此代碼將輸出屏幕分辨率。需要注意的是,pygetwindow
模塊需要安裝。可以通過運行 pip install pygetwindow
命令來安裝。
screeninfo
from screeninfo import get_monitors
for m in get_monitors():
print(f"屏幕分辨率為:{m.width} x {m.height}")
運行此代碼將輸出屏幕分辨率。需要注意的是,screeninfo
模塊需要安裝??梢酝ㄟ^運行 pip install screeninfo
命令來安裝。
tkinter
import tkinter as tk
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
print(f"屏幕分辨率為:{screen_width} x {screen_height}")
運行此代碼將輸出屏幕分辨率。需要注意的是,tkinter
需要在圖形界面環(huán)境中才能正常工作,因此此方法可能不適用于某些應(yīng)用程序或服務(wù)器環(huán)境。文章來源:http://www.zghlxwxcb.cn/news/detail-541439.html
pyautogui
import pyautogui
screen_width, screen_height = pyautogui.size()
print(f"屏幕分辨率為:{screen_width} x {screen_height}")
運行此代碼將輸出屏幕分辨率。文章來源地址http://www.zghlxwxcb.cn/news/detail-541439.html
到了這里,關(guān)于python --獲取本機屏幕分辨率的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!