- Getting Your Screen Resolution with Python
- Using the Linux Command Line
- Using PyGTK
- Using wxPython
- Using Tkinter
- Using PySide / PyQt
- Wrapping Up
- Additional Reading
- Как определить разрешение экрана?
- Решение
- Решение
- Retrieving Screen Resolution in Python: 4 Effective Methods
- Method 1: Pyautogui module
- Method 2: win32api module
- Method 3: wxPython module
- Method 4: Tkinter
- Conclusion.
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.
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
Как определить разрешение экрана?
Pygame и разрешение экрана
Доброго времени суток. У меня созрел вопрос: имеется ноутбук с разрешением экрана 1920 х 1080.
Как определить разрешение экрана
10,200,30,40 типа такое если такая картинку расширений чтобы знать как нарисовать картину
Как определить текущее разрешение экрана
Как определить текущее разрешение экрана?
Как програмно определить разрешение экрана ?
Как програмно определить разрешение экрана ?
Сообщение было отмечено gauka как решение
Решение
Сообщение от alex925
Сообщение от alex925
import Tkinter as tk root = tk.Tk() print root.winfo_screenwidth() print root.winfo_screenheight()
Сообщение было отмечено tezaurismosis как решение
Решение
Сообщение от gauka
Системная — из WinAPI. Все остальные — просто обертки.
# нужен pypywin32 для python >3.3 или pywin32 для from win32api import GetSystemMetrics print("width =", GetSystemMetrics(0)) print("height =", GetSystemMetrics(1))
from ctypes import * print(windll.user32.GetSystemMetrics(0)) print(windll.user32.GetSystemMetrics(1))
Сообщение от Garry Galler
ilnurgi,
Вернулся на сайт, чтобы как раз добавить — что это относится только к windows. Но не успел :-).
Добавлено через 1 минуту
А если кроссплатформенно подходить — тогда наверно лучше брать соответ. функции из GUI фрейморков.
Добавлено через 27 минут
Если через PyQt5, то например так:
import sys from PyQt5.QtWidgets import QDesktopWidget,QApplication app = QApplication(sys.argv) q= QDesktopWidget().availableGeometry() print("width =", q.width()) print("height =", q.height())
from ctypes import * print(windll.user32.GetSystemMetrics(0)) print(windll.user32.GetSystemMetrics(1)) import sys from PyQt5.QtWidgets import QDesktopWidget,QApplication #pip install PyQt5 app = QApplication(sys.argv) q= QDesktopWidget().availableGeometry() print("width =", q.width()) print("height =", q.height())
q= QDesktopWidget().geometry() print("width =", q.width()) print("height =", q.height())
Сообщение от iamvic
Ципихович Эндрю, вот у меня нет виндов и подцеплено два монитора 1600×1200 (screen0) и 1280×1024 (screen1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import sys from PyQt5.QtWidgets import QDesktopWidget,QApplication app = QApplication(sys.argv) q= QDesktopWidget().availableGeometry() print("QDesktopWidget().availableGeometry()") print("width =", q.width()) print("height =", q.height()) print() q= QDesktopWidget().geometry() print("QDesktopWidget().geometry()") print("width =", q.width()) print("height =", q.height()) print() q= QDesktopWidget().screenGeometry() print("QDesktopWidget().screenGeometry()") print("width =", q.width()) print("height =", q.height())
1 2 3 4 5 6 7 8 9 10 11 12
user@linux:~> python3 example.py QDesktopWidget().availableGeometry() width = 1600 height = 1160 QDesktopWidget().geometry() width = 2880 height = 1200 QDesktopWidget().screenGeometry() width = 1600 height = 1200
Рыть глубоко пока недосуг. Видимо что-то под заголовок окна (. ) резервируется в первом случае? ХЗ, как говорится.
Сообщение от Garry Galler
import sys from PyQt5.QtWidgets import QDesktopWidget,QApplication app = QApplication(sys.argv) q= QDesktopWidget().availableGeometry() print("width =", q.width()) print("height =", q.height())
Почему разрешение экрана планшета на 1280 x600 , а разрешение экрана проектора 854 x 480?
Привет всем, вчера я посмотрел такой плашет с проектором, разрешение экрана планшета на 1280 x600.
Как определить разрешение экрана в Access при помощи кода?
Буду признателен, если кто-то поможет в вопросе определения разрешения экрана из кода в Access, в.
Как получить масштаб элементов экрана или реальное разрешение экрана
Как получить разрешение экрана с учетом масштабирования, вот такой код и подобный ему дает неверный.
Как заменить разрешение экрана если его нету в параметрах экрана?
Я недавно установил Linux Mint 20, и схожу он ставит мне 1024×768 максимальным разрешением, хотя.
Как установить разрешение экрана 1440х900 если его нет в списке настроек экрана
По причине слабости компа скачал Виндовс 7 Реактор. Работает молниеносно, однако, есть весьма.
Определить разрешение экрана
Приветствую. Подскажите, как можно программно определить следующие моменты: 1. используемое.
Определить разрешение экрана
Всем привет! Я новичок в написании программ под линукс. У меня возникла такая проблема: пишу.
Retrieving Screen Resolution in Python: 4 Effective Methods
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:
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.
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
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?