Как проще всего получить разрешение монитора (желательно кортежем)?
Как получить разрешение монитора в Python?
Ответы (30)
В Windows:
from win32api import GetSystemMetrics
print("Width =", GetSystemMetrics(0))
print("Height =", GetSystemMetrics(1))
Если вы работаете с экраном с высоким разрешением, убедитесь, что ваш интерпретатор python имеет HIGHDPIAWARE.
На основе этого сообщения.
highdpiaware
? Это было бы полезно включить в ответ.
- person eric; 20.01.2019
В Windows вы также можете использовать ctypes с GetSystemMetrics()
:
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
так что вам не нужно устанавливать пакет pywin32; ему не нужно ничего, что не поставляется с самим Python.
Для настроек с несколькими мониторами вы можете получить общую ширину и высоту виртуального монитора:
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)
GetSystemMetrics(78)
и GetSystemMetrics(79)
?
- person Stevoisiak; 30.07.2018
Я создал модуль PyPI по этой причине:
pip install screeninfo
Код:
from screeninfo import get_monitors
for m in get_monitors():
print(str(m))
Результат:
monitor(1920x1080+1920+0)
monitor(1920x1080+0+0)
Он поддерживает среды с несколькими мониторами. Его цель - быть кроссплатформенной; на данный момент он поддерживает Cygwin и X11, но запросы на вытягивание полностью приветствуются.
pip install cython pyobjus
), прежде чем я смогу использовать его на OSX, хотя
- person George Profenza; 08.03.2019
Взято непосредственно из ответа на это сообщение: Как получить размер экрана в Tkinter?
import tkinter as tk
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
Если вы используете wxWindows, вы можете просто сделать:
import wx
app = wx.App(False) # the wx.App object must be created first.
print(wx.GetDisplaySize()) # returns a tuple
app = wx.App(False)
, иначе вы получите объект wx.App, который должен быть создан первым. ошибка. 26 голосов и никто не проверял? Работает ли в Windows без привязки экземпляра wx к переменной?
- person m3nda; 26.10.2015
В Windows 8.1 я не получаю правильного разрешения ни от ctypes, ни от tk. У других людей такая же проблема для ctypes: getsystemmetrics возвращает неправильный размер экрана Чтобы получить правильное полное разрешение монитора с высоким разрешением в Windows 8.1, необходимо вызвать SetProcessDPIAware и использовать следующий код:
import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
Полная информация ниже:
Я выяснил, что это потому, что окна сообщают о масштабированном разрешении. Похоже, что python по умолчанию является приложением, поддерживающим системное разрешение dpi. Типы приложений, поддерживающих DPI, перечислены здесь: http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor
По сути, вместо того, чтобы отображать контент с полным разрешением монитора, что сделало бы шрифты крошечными, контент масштабируется до тех пор, пока шрифты не станут достаточно большими.
На моем мониторе я получаю:
Физическое разрешение: 2560 x 1440 (220 точек на дюйм).
Сообщаемое разрешение Python: 1555 x 875 (158 точек на дюйм)
На этом сайте Windows: http://msdn.microsoft.com/en-us/library/aa770067%28v=vs.85%29.aspx Формула для расчета эффективного разрешения системы:
Я могу получить правильное полноэкранное разрешение и текущий DPI с помощью приведенного ниже кода. Обратите внимание, что я вызываю SetProcessDPIAware (), чтобы позволить программе увидеть реальное разрешение.
import tkinter as tk
root = tk.Tk()
width_px = root.winfo_screenwidth()
height_px = root.winfo_screenheight()
width_mm = root.winfo_screenmmwidth()
height_mm = root.winfo_screenmmheight()
# 2.54 cm = in
width_in = width_mm / 25.4
height_in = height_mm / 25.4
width_dpi = width_px/width_in
height_dpi = height_px/height_in
print('Width: %i px, Height: %i px' % (width_px, height_px))
print('Width: %i mm, Height: %i mm' % (width_mm, height_mm))
print('Width: %f in, Height: %f in' % (width_in, height_in))
print('Width: %f dpi, Height: %f dpi' % (width_dpi, height_dpi))
import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
print('Size is %f %f' % (w, h))
curr_dpi = w*96/width_px
print('Current DPI is %f' % (curr_dpi))
Что вернулось:
Width: 1555 px, Height: 875 px
Width: 411 mm, Height: 232 mm
Width: 16.181102 in, Height: 9.133858 in
Width: 96.099757 dpi, Height: 95.797414 dpi
Size is 2560.000000 1440.000000
Current DPI is 158.045016
Я использую Windows 8.1 с монитором с разрешением 220 точек на дюйм. При масштабировании дисплея мой текущий DPI равен 158.
Я использую 158, чтобы убедиться, что мои графики matplotlib имеют правильный размер: from pylab import rcParams rcParams ['figure.dpi'] = curr_dpi
Tkinter
использует правильные пиксели, но не знает о масштабировании точек на дюйм, поэтому сообщает неправильные размеры в миллиметрах.
- person Primer; 02.04.2015
ctypes.windll.shcore.SetProcessDpiAwareness(2)
возвращает ошибку OSError: [WinError 126] The specified module could not be found
.
- person Adrian Keister; 03.10.2018
winfo_screenmmwidth()
дает неверные результаты. Любые идеи?
- person Adrian Keister; 03.10.2018
И для полноты картины Mac OS X
import AppKit
[(screen.frame().size.width, screen.frame().size.height)
for screen in AppKit.NSScreen.screens()]
предоставит вам список кортежей, содержащих все размеры экрана (при наличии нескольких мониторов)
Если вы используете Qt
инструментарий конкретно PySide
, вы можете сделать следующее:
from PySide import QtGui
import sys
app = QtGui.QApplication(sys.argv)
screen_rect = app.desktop().screenGeometry()
width, height = screen_rect.width(), screen_rect.height()
Используя Linux, самый простой способ - выполнить команду bash
xrandr | grep '*'
и проанализируйте его вывод с помощью регулярного выражения.
Также вы можете сделать это через PyGame: http://www.daniweb.com/forums/thread54881.html
Кроссплатформенный и простой способ сделать это - использовать TKinter, который поставляется почти со всеми версиями Python, поэтому вам не нужно ничего устанавливать:
import tkinter
root = tkinter.Tk()
root.withdraw()
WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()
Вот небольшая небольшая программа на Python, которая отобразит информацию о вашей настройке с несколькими мониторами:
import gtk
window = gtk.Window()
# the screen contains all monitors
screen = window.get_screen()
print "screen size: %d x %d" % (gtk.gdk.screen_width(),gtk.gdk.screen_height())
# collect data about each monitor
monitors = []
nmons = screen.get_n_monitors()
print "there are %d monitors" % nmons
for m in range(nmons):
mg = screen.get_monitor_geometry(m)
print "monitor %d: %d x %d" % (m,mg.width,mg.height)
monitors.append(mg)
# current monitor
curmon = screen.get_monitor_at_window(screen.get_active_window())
x, y, width, height = monitors[curmon]
print "monitor %d: %d x %d (current)" % (curmon,width,height)
Вот пример его вывода:
screen size: 5120 x 1200
there are 3 monitors
monitor 0: 1600 x 1200
monitor 1: 1920 x 1200
monitor 2: 1600 x 1200
monitor 1: 1920 x 1200 (current)
gtk.Window()
получает gdk_default_root_window
? Так вы уверены, что .get_screen
содержит все мониторы?
- person yatg; 17.07.2015
gtk.Window()
создает новое окно (см. здесь). Окно - это всего лишь способ использовать get_screen
для получения информации о мониторе. Он возвращает экран, на котором окно открыто (или могло бы быть, если бы оно когда-либо отображалось). Я предполагаю, что от конфигурации X зависит, содержит ли этот экран все мониторы. Это работает в моей системе с Twinview.
- person starfry; 17.07.2015
Старый вопрос, но его нет. Я новичок в Python, поэтому скажите, пожалуйста, "плохое" ли это решение. Это решение поддерживается только для Windows и MacOS и работает только для главного экрана, но в вопросе не упоминается операционная система.
Измерьте размер, сделав снимок экрана. Поскольку размер экрана не должен меняться, это нужно делать только один раз. Есть более элегантные решения, если у вас установлен графический интерфейс, например GTK, wx, ...
см. Подушка
pip install Pillow
from PIL import ImageGrab
img = ImageGrab.grab()
print (img.size)
Расширение ответа @ user2366975, чтобы получить текущий размер экрана в многоэкранной настройке с использованием Tkinter (код на Python 2/3):
try:
# for Python 3
import tkinter as tk
except ImportError:
# for Python 2
import Tkinter as tk
def get_curr_screen_geometry():
"""
Workaround to get the size of the current screen in a multi-screen setup.
Returns:
geometry (str): The standard Tk geometry string.
[width]x[height]+[left]+[top]
"""
root = tk.Tk()
root.update_idletasks()
root.attributes('-fullscreen', True)
root.state('iconic')
geometry = root.winfo_geometry()
root.destroy()
return geometry
(Должен работать кросс-платформенный, протестирован только на Linux)
Я использую метод get_screen_resolution в одном из моих проектов, подобных приведенному ниже, который в основном представляет собой цепочку импорта. Вы можете изменить это в соответствии с вашими потребностями, удалив те части, которые не нужны, и переместите более вероятные порты вверх по цепочке.
PYTHON_V3 = sys.version_info >= (3,0,0) and sys.version_info < (4,0,0):
#[...]
def get_screen_resolution(self, measurement="px"):
"""
Tries to detect the screen resolution from the system.
@param measurement: The measurement to describe the screen resolution in. Can be either 'px', 'inch' or 'mm'.
@return: (screen_width,screen_height) where screen_width and screen_height are int types according to measurement.
"""
mm_per_inch = 25.4
px_per_inch = 72.0 #most common
try: # Platforms supported by GTK3, Fx Linux/BSD
from gi.repository import Gdk
screen = Gdk.Screen.get_default()
if measurement=="px":
width = screen.get_width()
height = screen.get_height()
elif measurement=="inch":
width = screen.get_width_mm()/mm_per_inch
height = screen.get_height_mm()/mm_per_inch
elif measurement=="mm":
width = screen.get_width_mm()
height = screen.get_height_mm()
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
return (width,height)
except:
try: #Probably the most OS independent way
if PYTHON_V3:
import tkinter
else:
import Tkinter as tkinter
root = tkinter.Tk()
if measurement=="px":
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
elif measurement=="inch":
width = root.winfo_screenmmwidth()/mm_per_inch
height = root.winfo_screenmmheight()/mm_per_inch
elif measurement=="mm":
width = root.winfo_screenmmwidth()
height = root.winfo_screenmmheight()
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
return (width,height)
except:
try: #Windows only
from win32api import GetSystemMetrics
width_px = GetSystemMetrics (0)
height_px = GetSystemMetrics (1)
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
try: # Windows only
import ctypes
user32 = ctypes.windll.user32
width_px = user32.GetSystemMetrics(0)
height_px = user32.GetSystemMetrics(1)
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
try: # Mac OS X only
import AppKit
for screen in AppKit.NSScreen.screens():
width_px = screen.frame().size.width
height_px = screen.frame().size.height
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
try: # Linux/Unix
import Xlib.display
resolution = Xlib.display.Display().screen().root.get_geometry()
width_px = resolution.width
height_px = resolution.height
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
try: # Linux/Unix
if not self.is_in_path("xrandr"):
raise ImportError("Cannot read the output of xrandr, if any.")
else:
args = ["xrandr", "-q", "-d", ":0"]
proc = subprocess.Popen(args,stdout=subprocess.PIPE)
for line in iter(proc.stdout.readline,''):
if isinstance(line, bytes):
line = line.decode("utf-8")
if "Screen" in line:
width_px = int(line.split()[7])
height_px = int(line.split()[9][:-1])
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
# Failover
screensize = 1366, 768
sys.stderr.write("WARNING: Failed to detect screen size. Falling back to %sx%s" % screensize)
if measurement=="px":
return screensize
elif measurement=="inch":
return (screensize[0]/px_per_inch,screensize[1]/px_per_inch)
elif measurement=="mm":
return (screensize[0]/mm_per_inch,screensize[1]/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
Версия для XWindows:
#!/usr/bin/python
import Xlib
import Xlib.display
resolution = Xlib.display.Display().screen().root.get_geometry()
print str(resolution.width) + "x" + str(resolution.height)
Если у вас установлен PyQt4, попробуйте следующий код:
from PyQt4 import QtGui
import sys
MyApp = QtGui.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))
Для PyQt5 будет работать следующее:
from PyQt5 import QtWidgets
import sys
MyApp = QtWidgets.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))
В Linux:
import subprocess
import re
def getScreenDimensions():
xrandrOutput = str(subprocess.Popen(['xrandr'], stdout=subprocess.PIPE).communicate()[0])
matchObj = re.findall(r'current\s(\d+) x (\d+)', xrandrOutput)
if matchObj:
return (int(matchObj[0][0]), int(matchObj[0][1]))
screenWidth, screenHeight = getScreenDimensions()
print(f'{screenWidth} x {screenHeight}')
Попробуйте pyautogui:
import pyautogui
resolution = pyautogui.size()
print(resolution)
Использование Linux Вместо регулярного выражения возьмите первую строку и выньте текущие значения разрешения.
Текущее разрешение дисплея: 0
>>> screen = os.popen("xrandr -q -d :0").readlines()[0]
>>> print screen
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 1920 x 1920
>>> width = screen.split()[7]
>>> print width
1920
>>> height = screen.split()[9][:-1]
>>> print height
1080
>>> print "Current resolution is %s x %s" % (width,height)
Current resolution is 1920 x 1080
Это было сделано на xrandr 1.3.5, я не знаю, отличается ли вывод в других версиях, но это должно упростить понимание.
Используя pygame:
import pygame
pygame.init()
infos = pygame.display.Info()
screen_size = (infos.current_w, infos.current_h)
Однако, если вы пытаетесь настроить окно на размер экрана, вы можете просто сделать:
pygame.display.set_mode((0,0),pygame.FULLSCREEN)
, чтобы перевести дисплей в полноэкранный режим. [2]
Чтобы получить бит на пиксель:
import ctypes
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32
screensize = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
print "screensize =%s"%(str(screensize))
dc = user32.GetDC(None);
screensize = (gdi32.GetDeviceCaps(dc,8), gdi32.GetDeviceCaps(dc,10), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
screensize = (gdi32.GetDeviceCaps(dc,118), gdi32.GetDeviceCaps(dc,117), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
параметры в gdi32:
#/// Vertical height of entire desktop in pixels
#DESKTOPVERTRES = 117,
#/// Horizontal width of entire desktop in pixels
#DESKTOPHORZRES = 118,
#/// Horizontal width in pixels
#HORZRES = 8,
#/// Vertical height in pixels
#VERTRES = 10,
#/// Number of bits per pixel
#BITSPIXEL = 12,
Другая версия с использованием xrandr
:
import re
from subprocess import run, PIPE
output = run(['xrandr'], stdout=PIPE).stdout.decode()
result = re.search(r'current (\d+) x (\d+)', output)
width, height = map(int, result.groups()) if result else (800, 600)
Многие из этих ответов используют tkinter для определения высоты / ширины (разрешения) экрана, но иногда необходимо знать dpi вашего кроссплатформенного экрана. Этот ответ взят по этой ссылке и оставлен как прокомментируйте другое сообщение, но поиск заняло несколько часов. У меня еще не было проблем с ним, но, пожалуйста, дайте мне знать, если он не работает в вашей системе!
import tkinter
root = tkinter.Tk()
dpi = root.winfo_fpixels('1i')
В документации для этого говорится:
winfo_fpixels(number)
# Return the number of pixels for the given distance NUMBER (e.g. "3c") as float
Число расстояния - это цифра, за которой следует единица измерения, поэтому 3c означает 3 сантиметра, а функция дает количество пикселей на 3 сантиметрах экрана (как здесь). Итак, чтобы получить dpi, мы запрашиваем у функции количество пикселей на 1 дюйм экрана (1i).
Если вы работаете в ОС Windows, вы можете использовать модуль ОС для его получения:
import os
cmd = 'wmic desktopmonitor get screenheight, screenwidth'
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))
Он вернет кортеж (Y, X), где Y - размер по вертикали, а X - размер по горизонтали. Этот код работает на Python 2 и Python 3
ОБНОВЛЕНИЕ
Для Windows 8 / 8.1 / 10 приведенный выше ответ не работает, используйте вместо него следующий:
import os
cmd = "wmic path Win32_VideoController get CurrentVerticalResolution,CurrentHorizontalResolution"
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))
Вы можете использовать PyMouse. Чтобы получить размер экрана, просто используйте атрибут screen_size()
:
from pymouse import PyMouse
m = PyMouse()
a = m.screen_size()
a
вернет кортеж (X, Y)
, где X
- горизонтальное положение, а Y
- вертикальное положение.
Ссылка на функцию в документации.
В Linux мы можем использовать модуль подпроцесса
import subprocess
cmd = ['xrandr']
cmd2 = ['grep', '*']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p.stdout, stdout=subprocess.PIPE)
p.stdout.close()
resolution_string, junk = p2.communicate()
resolution = resolution_string.split()[0]
resolution = resolution.decode("utf-8")
width = int(resolution.split("x")[0].strip())
heigth = int(resolution.split("x")[1].strip())
Это немного проблематично для экрана сетчатки, я использую tkinter, чтобы получить поддельный размер, используйте pilllow grab, чтобы получить реальный размер:
import tkinter
root = tkinter.Tk()
resolution_width = root.winfo_screenwidth()
resolution_height = root.winfo_screenheight()
image = ImageGrab.grab()
real_width, real_height = image.width, image.height
ratio_width = real_width / resolution_width
ratio_height = real_height/ resolution_height
Для более поздних версий PyGtk:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
display = Gdk.Display.get_default()
n_monitors = display.get_n_monitors()
print("there are %d monitors" % n_monitors)
for m in range(n_monitors):
monitor = display.get_monitor(m)
geometry = monitor.get_geometry()
print("monitor %d: %d x %d" % (m, geometry.width, geometry.height))
Для Linux вы можете использовать это:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
s = Gdk.Screen.get_default()
screen_width = s.get_width()
screen_height = s.get_height()
print(screen_width)
print(screen_height)
Сценарий утилиты с использованием библиотеки pynput
. Публикация здесь для исх .:
from pynput.mouse import Controller as MouseController
def get_screen_size():
"""Utility function to get screen resolution"""
mouse = MouseController()
width = height = 0
def _reset_mouse_position():
# Move the mouse to the top left of
# the screen
mouse.position = (0, 0)
# Reset mouse position
_reset_mouse_position()
count = 0
while 1:
count += 1
mouse.move(count, 0)
# Get the current position of the mouse
left = mouse.position[0]
# If the left doesn't change anymore, then
# that's the screen resolution's width
if width == left:
# Add the last pixel
width += 1
# Reset count for use for height
count = 0
break
# On each iteration, assign the left to
# the width
width = left
# Reset mouse position
_reset_mouse_position()
while 1:
count += 1
mouse.move(0, count)
# Get the current position of the mouse
right = mouse.position[1]
# If the right doesn't change anymore, then
# that's the screen resolution's height
if height == right:
# Add the last pixel
height += 1
break
# On each iteration, assign the right to
# the height
height = right
return width, height
>>> get_screen_size()
(1920, 1080)
Tkinter
вы можете сделать это таким образом. Это часть стандартной библиотеки Python и работает на большинстве платформ Unix и Windows. - person martineau   schedule 17.10.2010