Как сделать скриншот отдельного окна python

Обновлено: 03.05.2024

PyAutoGUI can take screenshots, save them to files, and locate images within the screen. This is useful if you have a small image of, say, a button that needs to be clicked and want to locate it on the screen. These features are provided by the PyScreeze module, which is installed with PyAutoGUI.

Screenshot functionality requires the Pillow module. OS X uses the screencapture command, which comes with the operating system. Linux uses the scrot command, which can be installed by running sudo apt-get install scrot .

Special Notes About Ubuntu¶

The screenshot() Function¶

Calling screenshot() will return an Image object (see the Pillow or PIL module documentation for details). Passing a string of a filename will save the screenshot to a file as well as return it as an Image object.

On a 1920 x 1080 screen, the screenshot() function takes roughly 100 milliseconds - it’s not fast but it’s not slow.

The Locate Functions¶

NOTE: As of version 0.9.41, if the locate functions can’t find the provided image, they’ll raise ImageNotFoundException instead of returning None .

You can visually locate something on the screen if you have an image file of it. For example, say the calculator app was running on your computer and looked like this:

_images/calculator.jpg

You can’t call the moveTo() and click() functions if you don’t know the exact screen coordinates of where the calculator buttons are. The calculator can appear in a slightly different place each time it is launched, causing you to re-find the coordinates each time. However, if you have an image of the button, such as the image of the 7 button:

_images/calc7key.jpg

… you can call the locateOnScreen('calc7key.jpg') function to get the screen coordinates. The return value is a 4-integer tuple: (left, top, width, height). This tuple can be passed to center() to get the X and Y coordinates at the center of this region. If the image can’t be found on the screen, locateOnScreen() raises ImageNotFoundException .

The optional confidence keyword argument specifies the accuracy with which the function should locate the image on screen. This is helpful in case the function is not able to locate an image due to negligible pixel differences:

Note: You need to have OpenCV installed for the confidence keyword to work.

The locateCenterOnScreen() function combines locateOnScreen() and center() :

On a 1920 x 1080 screen, the locate function calls take about 1 or 2 seconds. This may be too slow for action video games, but works for most purposes and applications.

There are several «locate» functions. They all start looking at the top-left corner of the screen (or image) and look to the right and then down. The arguments can either be a

  • locateOnScreen(image, grayscale=False) - Returns (left, top, width, height) coordinate of first found instance of the image on the screen. Raises ImageNotFoundException if not found on the screen.
  • locateCenterOnScreen(image, grayscale=False) - Returns (x, y) coordinates of the center of the first found instance of the image on the screen. Raises ImageNotFoundException if not found on the screen.
  • locateAllOnScreen(image, grayscale=False) - Returns a generator that yields (left, top, width, height) tuples for where the image is found on the screen.
  • locate(needleImage, haystackImage, grayscale=False) - Returns (left, top, width, height) coordinate of first found instance of needleImage in haystackImage . Raises ImageNotFoundException if not found on the screen.
  • locateAll(needleImage, haystackImage, grayscale=False) - Returns a generator that yields (left, top, width, height) tuples for where needleImage is found in haystackImage .

The «locate all» functions can be used in for loops or passed to list() :

These «locate» functions are fairly expensive; they can take a full second to run. The best way to speed them up is to pass a region argument (a 4-integer tuple of (left, top, width, height)) to only search a smaller region of the screen instead of the full screen:

Grayscale Matching¶

Optionally, you can pass grayscale=True to the locate functions to give a slight speedup (about 30%-ish). This desaturates the color from the images and screenshots, speeding up the locating but potentially causing false-positive matches.

Pixel Matching¶

To obtain the RGB color of a pixel in a screenshot, use the Image object’s getpixel() method:

Or as a single function, call the pixel() PyAutoGUI function, which is a wrapper for the previous calls:

If you just need to verify that a single pixel matches a given pixel, call the pixelMatchesColor() function, passing it the X coordinate, Y coordinate, and RGB tuple of the color it represents:

The optional tolerance keyword argument specifies how much each of the red, green, and blue values can vary while still matching:

With python 3, I'd like to get a handle to another window (not part of my application) such that I can either:

  1. directly capture that window as a screenshot, or
  2. determine its position and size and capture it some other way

In case it is important, I am using Windows XP (edit: works in Windows 7 also).

I found this solution, but it is not quite what I need since it is full screen and more importantly, PIL to the best of my knowledge does not support 3.x yet.

News Flash: The Pillow fork of the PIL does support Python 3 and features a working ImageGrab module, and also has excellent documentation.

If somebody adds that as an answer, I'd move the selected answer and update the question. It's certainly the best option today.

KobeJohn: Pillow currently doesn't have a way to capture to capture a single application's window, just the whole screen, so the currently accepted answer is still relevant at least for the Windows OS. Unfortunately what's really needed is a portable way to determine the window location of applications.

4 Answers 4

Here's how you can do it using PIL on win32. Given a window handle ( hwnd ), you should only need the last 4 lines of code. The preceding simply search for a window with "firefox" in the title. Since PIL's source is available, you should be able to poke around the ImageGrab.grab(bbox) method and figure out the win32 code you need to make this happen.

That looks great if I understand it correctly. PIL won't work directly but I can use win32gui in Python 3k to get the window as you showed and then extract the win32 code from PIL to do the grab. Is that right? I'll try it out as soon as I can set aside the time.

I'm still new to both python and win32, but this certainly seems to be going the right direction. I'll post more specific code here if I figure it out for anyone else that might need it.

So this is not working out so well for me at the moment. I was able to get a handle to the window as you showed. Thanks very much for that. However, when I dug down, I believe ImageGrab ends up in a c file named display.c that comes with PIL. The function there is PyImaging_GrabScreenWin32. I'm going to research whether I can use that myself, but in the meantime, does anyone know a way to get a screenshot in Python 3k without needing to compile and interface to a c library myself?

That worked! Those are quite similar to what happens in display.c. I didn't realize that much of the interface was available in Python already through the other libraries. Thanks for the invaluable follow-up ars.

webfanat вконтакте
webfanat youtube

Скриншоты python

Скриншоты python

Всем привет. Сегодня мы рассмотрим как делать скриншоты в python используя модуль pyautogui. Поехали!

Для начала подключаем модуль pyautogui.

И теперь для того чтобы сделать скриншот, достаточно воспользоваться методом screenshot() который предоставляет нам данный модуль.

В результате выполнения данного кода мы сделаем скриншот всего экрана. Сам скриншот сохранится в виде изображения с названием screenshot и в формате png. Которые мы указали в самом методе screenshot(). Найти изображение вы сможете рядом с файлом программы. На выходе метод screenshot() возвращает объект изображения.

Если мы хотим сделать скриншот определенной части экрана. Можно воспользоваться свойством region.

Здесь в свойстве region мы указали что у нас будет снят левый верхний угол размером 300x400 пикселей. То есть первые две координаты(0,0) отвечают за левый верхний угол, а вторые(300, 400) за размер области экрана.

Вот мы у научились делать скриншоты в python. Помимо этого модуль pyautogui предоставляет нам возможность нахождения кусочков изображения в области где мы осуществляем скриншот.

Допустим у меня есть такой кусочек изображения.

mozilla firefox

Кто не знает это значок браузера mozilla firefox.

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

screenshot python

Для этого я использую метод locateOnScreen() и в качестве аргумента передаю ему изображение со значком.

В результате работы данный метод возвращает координаты где было найдено соответствие с изображением значка в области всего экрана.

Если я к примеру удалю ярлык браузера mozilla firefox из области экрана. Следовательно соответствия метод locateOnScreen() уже не найдет и нам вернется значение None.

screenshot python pyautogui

Вот так с помощью метода locateOnScreen() вы можете в области экрана искать соответствия по картинке шаблону.

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

А я с вами прощаюсь. Желаю успехов и удачи! Пока.

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

Статьи

Комментарии

Внимание. Комментарий теперь перед публикацией проходит модерацию

Все комментарии отправлены на модерацию

Реклама

Запись экрана

Данное расширение позволяет записывать экран и выводит видео в формате webm

Hey guys, taking screenshot is necessary for most of the application so in this post you will learn how to take screenshot using python. So let’s start Python Screenshot Tutorial.

There are various ways to take screenshot using python. The first and most popular way is using PyAutoGUI module. You can also use pillow module for taking screenshots in python. And you will also learn here, how to take screenshots in tkinter application. So let’s move towards our main topic.

Python Screenshot Tutorial – Getting Started

Taking Screenshot Using PyAutoGUI

PyAutoGUI is a cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.

Installing PyAutoGUI

To install PyAutoGUI module, you have to run following code on your command prompt.

Code For Screenshot Using PyAutoGUI

  • screenshot( ) method of pyautogui class is used to take screenshot of your screen.

Now write the following code on your python IDE.

  • First of all import pyautogui module.
  • Then create a variable(file) that will store the screenshot.
  • screenshot( ) method will take screenshot of your screen.
  • Now save this image by calling save( ) method. You have to pass name of screenshot to the save( ) function.

Let’s check the output –

Taking Screenshot With Time

In the above example, you have seen that the screenshot of current screen is captured, but if you want to take screenshot of another screen such as your desktop or anything else, so what can you do. For this you have to use time module. sleep( ) method of time module is used to add delay in the execution of a program.

So now write the following program.

  • Firstly import time module.
  • Then call sleep( ) method and pass an argument which is your delay time. Here i am passing 6, you can pass as much you want.
  • Now run the code and go to desktop or wherever you want to take screenshot. After 6 second it will take screenshot of your screen.

Now lets check the output.

Python Screenshot

Python Screenshot

Taking Screenshot Using Pillow

    is a Python Imaging Library (Fork).
  • The Python Imaging Library adds image processing capabilities to your Python interpreter.
  • This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities.

Installing Pillow

Now run the following command on to your command prompt.

Code Snippet

Now you will see how to take screenshot using pillow module. So let’s start.

Pillow has a ImageGrab class which is used to copy the contents of the screen. grab( ) method is used to take screen shot.

Write the following code snippets.

  • bbox is the region which is to be copied.
  • bbox is consist of tuple. It has four values – the first one is value of x, second one is value of y, third one is value of width and fourth one is value of height.
  • The pixels inside the bounding box are returned as an “RGB” image on Windows or “RGBA” on OS X.
  • If bbox is not passed then the entire screen will be captured.

Now lets see the output.

Python Screenshot

Python Screenshot

Taking Screenshot Using Keyboard

In this section you will see how to take screen shot by pressing key from keyboard. Keyboard is a small Python library which can hook global events, register hotkeys, simulate key presses and much more.

Installing Keyboard Module

Run the following command to install keyboard module.

Code Snippet

Now write the following code to achieve the above task.

  • In this example i have passed p key as an argument to is_pressed( ) method. That means whenever you will enter p key from keyboard, your current screen will be captured.
  • Now run the code and go to the place wherever you want and now just press p key from keyboard. It will take the screenshot of your screen.

Now lets check the output. Here i have opened start option and press the p key from keyboard. So it has taken following output.

Python Screenshot

Python Screenshot

Taking Screenshot Using An Tkinter application

Now you will learn how to take screenshot from a Tkinter application.

So write the following code snippets on your editor.

Now run the above code. Now a GUI window will be appeared, now press the button present on this window. Your screen has been captured. Let’s see the output.

Python Screenshot

Python Screenshot

Conclusion

So guys, you have learned many ways to take screenshot using python. PyAutoGUI and Pillow is the two most important python library to take screenshot in python. It is very easy to implement. I hope you have learned a lot of valuable thing in Python Screenshot tutorial. If you have any query then ask here, i will try to short out your problems. And stay tuned with SIMPLIFIED PYTHON for latest and important tutorials. Thanks Everyone.

С помощью python 3 я хотел бы получить дескриптор другого окна (не часть моего приложения), чтобы я мог:

а) непосредственно захватить это окно как снимок экрана или

б) определить его положение и размер и зафиксировать другим способом

Если это важно, я использую Windows XP (редактировать: работает и в Windows 7).

Я нашел это решение, но это не совсем то, что мне нужно, поскольку оно полноэкранный режим и, что более важно, PIL, насколько мне известно, еще не поддерживает 3.x.

4 ответа

Вот как это можно сделать с помощью PIL на win32. Учитывая дескриптор окна ( hwnd ), вам понадобятся только последние 4 строки кода. Предыдущее просто поиск окна с "firefox" в заголовке. Поскольку доступен исходный код PIL, вы должны иметь возможность ковыряться в методе ImageGrab.grab(bbox) и вычислять код Win32, который вам нужен, чтобы это произошло.

Решение здесь получает снимок экрана с одним окном (поэтому может работать, если окно находится в фоновом режиме).

Другие решения этой страницы делают снимок той части экрана, на которой находится окно, и поэтому сначала необходимо вывести окно на передний план.

Это приведет к созданию нового открытого окна и его снимка экрана, а затем его кадрирования с помощью PIL, также возможно найти ваше конкретное окно с помощью pygetwindow.getAllTitles (), а затем заполнить имя вашего окна в z3, чтобы получить снимок экрана только этого окна.

Если вы определенно не хотите использовать PIL, вы можете развернуть окно с помощью модуля pygetwindow, а затем сделать снимок экрана с модулем pyautogui.

Примечание: не тестировалось в Windows XP (но тестировалось в Windows 10)

Арс отдал мне все детали. Я просто собираю здесь кусочки для всех, кому нужно сделать снимок экрана в python 3.x. Затем мне нужно выяснить, как работать с растровым изображением win32, не опираясь на PIL.

Получить снимок экрана (передать hwnd для окна вместо полноэкранного):

Получить дескриптор окна по заголовку (для перехода к вышеуказанной функции):

Читайте также: