如何在 Python 3k 中获取窗口或全屏截图?(不含 PIL) [英] How to Get a Window or Fullscreen Screenshot in Python 3k? (without PIL)

查看:42
本文介绍了如何在 Python 3k 中获取窗口或全屏截图?(不含 PIL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 python 3,我想获得另一个窗口(不是我的应用程序的一部分)的句柄,以便我可以:

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

a) 直接捕获该窗口作为屏幕截图或

a) directly capture that window as a screenshot or

b) 确定它的位置和大小并以其他方式捕获它

b) determine its position and size and capture it some other way

以防万一,我使用的是 Windows XP(也适用于 Windows 7).

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

我找到了这个解决方案,但这并不是我所需要的因为它是全屏的,更重要的是,据我所知,PIL 还不支持 3.x.

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.

推荐答案

以下是在 win32 上使用 PIL 的方法.给定一个窗口句柄 (hwnd),您应该只需要最后 4 行代码.前面只是搜索标题中带有firefox"的窗口.由于 PIL 的源代码可用,您应该能够浏览 ImageGrab.grab(bbox) 方法并找出实现此目的所需的 win32 代码.

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.

from PIL import ImageGrab
import win32gui

toplist, winlist = [], []
def enum_cb(hwnd, results):
    winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
win32gui.EnumWindows(enum_cb, toplist)

firefox = [(hwnd, title) for hwnd, title in winlist if 'firefox' in title.lower()]
# just grab the hwnd for first window matching firefox
firefox = firefox[0]
hwnd = firefox[0]

win32gui.SetForegroundWindow(hwnd)
bbox = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox)
img.show()

这篇关于如何在 Python 3k 中获取窗口或全屏截图?(不含 PIL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆