Python получить размер монитора

Как получить разрешение монитора в Python?

С модулем Tkinter вы можете сделать это следующим образом . Он является частью стандартной библиотеки Python и работает на большинстве платформ Unix и Windows.

20 ответов

так что вам не нужно устанавливать пакет pywin32; ему не нужно ничего, что не связано с самим Python.

Важное примечание: возвращаемые значения могут быть неправильными, если используется масштабирование DPI (то есть: часто это происходит на дисплеях 4k), вам необходимо вызвать SetProcessDPIAware перед инициализацией компонентов GUI (а не перед вызовом функции GetSystemMetrics). Это верно для большинства ответов здесь (GTK и т. Д.) На платформе win32.

@StevenVascellaro Ширина / высота виртуального экрана в пикселях. msdn.microsoft.com/en-us/library/windows/desktop/.

FYI Я создал модуль PyPI по этой причине:

from screeninfo import get_monitors for m in get_monitors(): print(str(m)) 
monitor(1920x1080+1920+0) monitor(1920x1080+0+0) 

Он поддерживает среды с несколькими мониторами. Его цель — быть кросс-платформой; на данный момент он поддерживает Cygwin и X11, но запросы на передачу полностью приветствуются.

Отлично работает на Windows, но Mac Я получаю следующую ошибку: ImportError: Не удалось загрузить X11

К вашему сведению, масштабирование DPI по-прежнему применяется. Эта строка сообщит Windows, что вам нужно исходное, немасштабированное разрешение: «import ctypes; user32 = ctypes.windll.user32; user32.SetProcessDPIAware ()». 1) Ваш ответ должен быть верхним; хорошая работа. 2) Мой комментарий относится к Windows, а не к библиотеке (например, screeninfo) 3) код разорван и протестирован из комментария КобеДжона здесь: stackoverflow.com/a/32541666/2616321

Удобный модуль (+1). Мне пришлось установить пару требований (например, pip install cython pyobjus ), прежде чем я смог использовать его в OSX

Если вы используете wxWindows, вы можете просто:

import wx app = wx.App(False) # the wx.App object must be created first. print(wx.GetDisplaySize()) # returns a tuple 

Это лучший . у кого нет wx? 🙂 плюс несколько строк вместо кучки кода на ваших глазах. Теперь это мой метод по умолчанию, спасибо.

Это должно быть app = wx.App(False) иначе вы получите «объект wx.App должен быть создан первым». ошибка. 26 голосов а никто не проверял? Работает ли в Windows, не назначая экземпляр wx переменной?

Взято непосредственно из ответа на этот пост: Как получить размер экрана в Tkinter?

import tkinter as tk root = tk.Tk() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() 

Если у вас есть внешние дисплеи, расширенные до основного дисплея, этот метод даст сумму всех разрешений дисплея, а не текущего разрешения дисплея.

В Windows 8.1 я не получаю правильное разрешение от ctypes или tk. У других людей такая же проблема для ctypes: getsystemmetrics возвращает неправильный размер экрана Чтобы получить правильное полное разрешение высокого монитора DPI на окнах 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 DPI)
Сообщенное разрешение python: 1555 x 875 (158 DPI)

В этом окне: http://msdn.microsoft.com/en-us/library/aa770067%28v=vs.85%29.aspx Формула для эффективного разрешения системы: (сообщено_px * current_dpi)/(96 dpi) = физическое_px

Я могу получить правильное полноэкранное разрешение и текущий 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. Мое масштабирование экрана устанавливает мой текущий DPI на 158.

Я буду использовать 158, чтобы убедиться, что мои графики matplotlib имеют нужный размер: из pylab import rcParams rcParams [‘figure.dpi’] = curr_dpi

У вас есть много полезной информации здесь, но сам ответ похоронен в середине. Чтобы вам было легче читать, можете ли вы уточнить, какой именно ответ, а затем предоставить справочную информацию?

Я отредактировал свой пост, чтобы сначала показать ответ, а затем углубиться в детали. Спасибо за ответ.

Похоже, что здесь есть недостатки в вычислениях, которые легко заметить, если вы вычислите размер диагонали по сообщенной ширине и высоте (в дюймах). Мой экран с диагональю 13,3 дюйма был отмечен как 15 дюймов. Кажется, что Tkinter использует правильные пиксели, но не знает о масштабировании точек на дюйм, поэтому сообщает о неверных размерах в мм.

Это не работает в Windows 10, там SetSystemDPIAware (), похоже, не имеет значения. Тем не менее, вызов ctypes.windll.shcore.SetProcessDpiAwareness (2) вместо этого, кажется, делает свое дело.

@KlamerSchutte: ctypes.windll.shcore.SetProcessDpiAwareness(2) возвращает ошибку OSError: [WinError 126] The specified module could not be found .

@spacether: этот код не работает в Windows 7, 64-разрядная версия. Я получаю ширину окна и высоту окна, которые далеко. Функция winfo_screenmmwidth() дает неверные результаты. Есть идеи?

@AdrianKeister на вашем месте, я бы попробовал другое input_value: user32.GetSystemMetrics (input_value) Возможные значения перечислены здесь: docs.microsoft.com/en-us/windows/desktop/api/winuser/… и покопаться в том, что ваши текущие результаты получены от wx, что они от user32, в чем разница, и если это отличие от проблемы DPI.

@spacether: я просмотрел документацию MS, на которую вы ссылались. К сожалению, нет методов для определения dpi или коэффициента конверсии. Все в пикселях. Согласно спецификации на моем мониторе, похоже, что он возвращает правильное количество пикселей. Но плотность определенно выше, чем 96 точек на дюйм, так как у меня нет монитора с диагональю 20 дюймов. User32 возвращает числа, очень близкие к значениям tkinter.

В этих документах @AdrianKeister указано, что эти методы не поддерживают dpi. Поиск DPI в этих документах показывает, что вы должны изучить docs.microsoft.com/en-us/windows/desktop/api/winuser/… и docs.microsoft.com/en-us/windows/desktop/hidpi/…

@spacether: Отлично, спасибо! Я проверю это, как только вернусь с моей машиной Windows. Прямо сейчас у меня есть экспериментальное решение, где я физически измерил свой монитор и получил эмпирическое dpi. Это работает довольно хорошо, но это, очевидно, было бы более элегантно, если бы я мог заставить его работать.

Источник

Retrieving Screen Resolution in Python: 4 Effective Methods

HOW TO GET SCREEN RESOLUTION IN PYTHON

Screen resolution is the number of pixels that can be displayed in each dimension on your computer screen or monitor. It is important to know the screen resolution of your computer because it helps us analyse the quality of videos and images. If the resolution of the screen is high then it can process greater pixel information and can provide high end graphics.

Knowing your screen resolution helps you to understand what kind of images your computer can display with how much clarity. In programming, knowing your screen resolution is essential to comprehend how much output can fit on your screen.

People who design games need clear screen resolution details to analyse the amount of graphic they can fit on the display screen and write code accordingly.

There are many ways in which you can find out the screen resolution via Python. You can do it using some special modules or without them. We’ll look at some of those methods in this tutorial in the following sections.

Method 1: Pyautogui module

The Pyautogui module is a Python module that can be used across all operating systems such as windows, macOS or Linux to recognize mouse or cursor movements or keyboard clicks. It is used for a number of purposes mainly in order to design UI systems.

When you install Python, the Pyautogui module is supposed to be pre installed with some other packages. But if for some reason your system doesn’t have this library, run the following code in your command prompt in administrator mode.

Your installation should look something like this:

Glimpse Of Pyautogui Installation Process

Now you just need to import this module into your Python shell and you can easily get the monitor resolution in the form of (width, height) as a tuple.

>>import pyautogui >>pyautogui.size() Size(width=1366, height=768)

Method 2: win32api module

The win32api in Python is used for creating and deploying 32 bit applications using python. It can also be used for getting the screen resolution as well. They are mainly used for configuring administrative system files in your computer.

This module can be installed by running the following code in your command prompt or shell in administrator mode using pip if you’re using windows. This module works for all operating systems.

Now, open your Python shell and import the module and run the following code:

>>import win32api >>from win32api import GetSystemMetrics >>print('The Width is= ', GetSystemMetrics(0)) The Width is= 1366 #output for width >>print('The Height is= ', GetSystemMetrics(1)) The Height is= 768 #output for height

So, in the shell, we have got the width and height of our screen as required as shown above.

Using Win32APi And GetSystemMetrics

Method 3: wxPython module

The wx module in Python is used as an alternate to tkinter as an extension module. It is a wrapper for the GUI based application wxwidgets for Python. You can install it by running the following command in your windows system, although it can be used for all other operating systems as well.

Now you can use this module to get the screen resolution in Python.

import wx outp= wx.App(False) width, height= wx.GetDisplaySize() print("The width is= " + str(width) + " and the height is= " + str(height))

The output would be as follows:

The width is= 1366 and the height is= 768

Using The Wx Wrapper To Find Our Screen Resolution

Method 4: Tkinter

The tkinter module is one of the most popular GUI tool that is used to create widgets using C commands in python. It is very popular among developers for creating User interface designs. You can also use this module to check your screen resolution by creating an object and then following the rest of the code:

import tkinter app = tkinter.Tk() width = app.winfo_screenwidth() height = app.winfo_screenheight() print("width=",width) print("height=",height)

The output would be something like this:

Conclusion.

In this article, we have gone through 4 of the easiest methods to determine our screen resolution. Screen resolution information is important for a variety of reasons such as, for game development, for creating user interfaces, etc. Due to the vast availability of Python modules, determining your monitor’s information is easier than you think. Which of these methods do you think you’re going to use in your next project?

Источник

Читайте также:  Php проверка целое положительное число
Оцените статью