Узнать разрешение монитора python

Getting Your Screen Resolution with Python

I was recently looking into ways to get my screen resolution with Python to help diagnose an issue with an application that wasn’t behaving correctly. In this article, we’ll look at some of the ways to get your screen resolution. Not all of the solutions will be cross-platform, but I’ll be sure to mention that fact when I discuss those methods. Let’s get started!

Using the Linux Command Line

There are several ways to get your screen resolution in Linux. If you do a Google search, you’ll see people using various Python GUI toolkits. I wanted to find a way to get the screen resolution without installing a third party module. I eventually found the following command:

I then had to take that information and translate it into Python. Here’s what I came up with:

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] width, height = resolution.split('x')

Whenever you need to pipe data with Python, you will need to create two different subprocess instances. That is what I did above. I piped the output from xrandr to my second subprocess via its stdin. Then I closed the stdout of the first process to basically flush whatever it had returned to the second process. The rest of the code just parses out the width and height of the monitor.

Читайте также:  Чего начать изучать php

Using PyGTK

Of course the above method is Linux-only. If you happen to have PyGTK installed, then you can get your screen resolution using that. Let’s take a look:

import gtk width = gtk.gdk.screen_width() height = gtk.gdk.screen_height()

That was pretty straightforward as PyGTK has those methods built-in. Note that PyGTK is available for Windows and Linux. There is supposed to be a Mac version in development as well.

Using wxPython

As you might expect, the wxPython toolkit also provides a method for getting your screen resolution. It’s a bit less useful in that you actually need to create an App object before you can get the resolution though.

import wx app = wx.App(False) width, height = wx.GetDisplaySize()

This is still an easy way to get the resolution you’re looking for. It should also be noted that wxPython runs on all three major platforms.

Using Tkinter

The Tkinter library is usually included with Python, so you should have this one be default. It also provides screen resolution, although it requires you to create an “app” object too:

import Tkinter root = Tkinter.Tk() width = root.winfo_screenwidth() height = root.winfo_screenheight()

Fortunately, Tkinter is also available on all 3 major platforms, so you can use this method pretty much anywhere.

Using PySide / PyQt

As you’ve probably guessed, you can also get the screen resolution using PySide and PyQt. Here’s the PySide version:

from PySide import QtGui app = QtGui.QApplication([]) screen_resolution = app.desktop().screenGeometry() width, height = screen_resolution.width(), screen_resolution.height()

If you have PyQt4 instead, then you’ll want to change the import at the beginning to the following:

The rest is the same. And as you probably know, both of these libraries are available on Windows, Linux and Mac.

Wrapping Up

At this point, you should be able to get the screen resolution on any OS you’re on. There are additional methods of getting this information that are platform dependent. For example, on Windows you can use PyWin32’s win32api or ctypes. On Mac, there is AppKit. But the toolkit methods listed here will work on most platforms just fine and because they’re cross-platform, you won’t need to use special cases to import specific packages to make this work.

Additional Reading

Источник

Get the Monitor Resolution in Python

Get the Monitor Resolution in Python

Many operations involve developing GUI in Python to interact with applications and operating systems. So to perform these kinds of procedures, Python provides multiple packages and libraries. One of the tasks that include the GUI is getting the resolution of the monitor.

This tutorial will show you a method on how to get the resolution of the monitor in Python.

the Use of the Tkinter Library in Python

The Tkinter package is Python’s GUI library. This library helps Python by providing a GUI tool kit that helps in developing GUI applications. By using this library, Python can interact with other applications easily. Check this example code below.

from tkinter import *  root = Tk()  monitor_height = root.winfo_screenheight() monitor_width = root.winfo_screenwidth()  print("width x height = %d x %d (pixels)" %(monitor_width, monitor_height)) mainloop() 
width x height = 1440 x 900 (pixels) 

In the program above, we import the tkinter library first. Then, in the next step, we create a root window , which is basically the main application window in the applications. You must define this window before performing any operation on any application.

After that, we get the dimensions of the monitor by using the root.winfo_screenheight() and root.winfo_screenwidth() methods, respectively. Note that the values returned are in pixels .

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.

Источник

Получение разрешения экрана в Python: 4 эффективных метода

Разрешение экрана — это количество пикселей, которое может отображаться в каждом измерении на экране вашего компьютера или мониторе. Важно знать разрешение экрана вашего компьютера, потому что это помогает нам анализировать качество видео и изображений. Если разрешение экрана высокое, то он может обрабатывать больше информации о пикселях и может обеспечивать высококачественную графику.

Знание разрешения экрана поможет вам понять, какие изображения с какой четкостью может отображать ваш компьютер. В программировании знание разрешения экрана необходимо для понимания того, сколько вывода может поместиться на вашем экране.

Людям, разрабатывающим игры, нужны четкие данные о разрешении экрана, чтобы проанализировать количество графики, которое они могут уместить на экране, и соответствующим образом написать код.

Есть много способов узнать разрешение экрана с помощью Python. Вы можете сделать это с помощью специальных модулей или без них. Мы рассмотрим некоторые из этих методов в этом руководстве в следующих разделах.

Способ 1: модуль Pyautogui

Пьяаутоги module — это модуль Python, который можно использовать во всех операционных системах, таких как Windows, macOS или Linux, для распознавания движений мыши или курсора или щелчков клавиатуры. Он используется для ряда целей, в основном для разработки систем пользовательского интерфейса.

Когда вы устанавливаете Python, модуль Pyautogui должен быть предварительно установлен с некоторыми другими пакетами. Но если по какой-то причине в вашей системе нет этой библиотеки, запустите следующий код в командной строке в режиме администратора.

Ваша установка должна выглядеть примерно так:

Взгляд на процесс установки Pyautogui

Теперь вам просто нужно импортировать этот модуль в вашу оболочку Python, и вы можете легко получить разрешение монитора в виде (ширины, высоты) в виде кортежа.

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

Связанный: Автоматизация с PyAutoGUI в Python.

Способ 2: модуль win32api

win32api в Python используется для создания и развертывания 32-битных приложений с использованием Python. Его также можно использовать для получения разрешения экрана. В основном они используются для настройки административных системных файлов на вашем компьютере.

Этот модуль можно установить, запустив следующий код в командной строке или оболочке в режиме администратора, используя pip, если вы используете Windows. Этот модуль работает для всех операционных систем.

Теперь откройте оболочку Python, импортируйте модуль и запустите следующий код:

>>import win32api >>from win32api import GetSystemMetrics >>print('The Width is=", GetSystemMetrics(0)) The Width is= 1366 #output for width >>print("The Height is yandex_rtb_R-A-2079046-8">
Использование Win32APi и GetSystemMetrics
Использование Win32APi и GetSystemMetrics

Способ 3: модуль wxPython

wx модуль в Python используется как альтернатива tkinter в качестве модуля расширения. Это оболочка для приложения wxwidgets с графическим интерфейсом для Python. Вы можете установить его, выполнив следующую команду в своей системе Windows, хотя ее можно использовать и для всех других операционных систем.

Теперь вы можете использовать этот модуль для получения разрешения экрана в Python.

import wx outp= wx.App(False) width, height= wx.GetDisplaySize() print("The width is= " + str(width) + " and the height is wp-block-syntaxhighlighter-code "> 
The width is= 1366 and the height is= 768

Использование Wx Wrapper для определения разрешения экрана

Метод 4: Ткинтер

ткинтер module — один из самых популярных инструментов с графическим интерфейсом, который используется для создания виджетов с помощью команд C в python. Он очень популярен среди разработчиков для создания дизайна пользовательского интерфейса. Вы также можете использовать этот модуль для проверки разрешения экрана, создав объект и следуя остальной части кода:

import tkinter app = tkinter.Tk() width = app.winfo_screenwidth() height = app.winfo_screenheight() print("width=",width) print("height wp-block-heading">Заключение.

В этой статье мы рассмотрели 4 самых простых метода определения разрешения экрана. Информация о разрешении экрана важна по целому ряду причин, например, для разработки игр, создания пользовательских интерфейсов и т. д. Из-за широкой доступности модулей Python определить информацию о вашем мониторе проще, чем вы думаете. Как вы думаете, какой из этих методов вы собираетесь использовать в своем следующем проекте?

Источник

Оцените статью