Python特定窗口截图捕获范围超出预期的问题求助
窗口截图范围超出实际尺寸的问题
我开发的截图小程序全屏截图功能正常,但捕获特定窗口时,截图范围会超出窗口实际尺寸,且不同窗口的多余像素量存在差异。原实现代码如下:
import keyboard, win32gui from tkinter import filedialog import pyautogui as pg # Open file explorer for save file in a location def save_file(): global file filetypes = [("PNG files", ".png"), ("JPG files", ".jpg"), ("All files", "*")] file = filedialog.asksaveasfilename(defaultextension=".png", filetypes=filetypes, initialdir="C:/Users/Prado/Imágenes/Screenshoots", initialfile="my_screenshoot") # Take a screenshot of the entire screen def full_screenshot(): save_file() pg.screenshot(file) # Take a screenshot of a specific window def window_screenshot(): save_file() w = win32gui window_region = w.GetWindowRect(w.FindWindow(None, w.GetWindowText(w.GetForegroundWindow()))) # Get position and size of the current window pg.screenshot(file, region=window_region) print(window_region) keyboard.add_hotkey("alt + insert", window_screenshot) keyboard.add_hotkey("ctrl + insert", full_screenshot) keyboard.wait("esc")
问题原因
win32gui.GetWindowRect() 获取的是窗口的边框外矩形,包含了Windows窗口的标题栏、边框阴影(尤其是Win10/11的圆角窗口),而pyautogui的region参数基于这个矩形截图,所以会包含额外区域。
修复方案
改用win32gui.GetClientRect()获取窗口客户区(仅内容显示区域),再通过win32gui.ClientToScreen()转换为屏幕绝对坐标,以此构造精准的截图区域。
修改后的完整代码
import keyboard, win32gui from tkinter import filedialog import pyautogui as pg # 打开文件选择器保存截图 def save_file(): global file filetypes = [("PNG files", ".png"), ("JPG files", ".jpg"), ("All files", "*")] file = filedialog.asksaveasfilename(defaultextension=".png", filetypes=filetypes, initialdir="C:/Users/Prado/Imágenes/Screenshoots", initialfile="my_screenshoot") # 全屏截图 def full_screenshot(): save_file() pg.screenshot(file) # 窗口截图(修复版) def window_screenshot(): save_file() w = win32gui hwnd = w.GetForegroundWindow() # 获取客户区相对矩形(窗口内容区域,不含边框) client_rect = w.GetClientRect(hwnd) # 将客户区左上角、右下角坐标转换为屏幕绝对坐标 left, top = w.ClientToScreen(hwnd, (client_rect[0], client_rect[1])) right, bottom = w.ClientToScreen(hwnd, (client_rect[2], client_rect[3])) # 构造pyautogui所需的region参数:(left, top, width, height) window_region = (left, top, right - left, bottom - top) pg.screenshot(file, region=window_region) print(window_region) keyboard.add_hotkey("alt + insert", window_screenshot) keyboard.add_hotkey("ctrl + insert", full_screenshot) keyboard.wait("esc")
关键修改说明
GetClientRect():仅获取窗口内部内容区域的相对坐标(左上角为(0,0)),不包含边框、标题栏和阴影。ClientToScreen():将客户区的相对坐标转换为屏幕上的绝对坐标,确保截图位置正确。- 最终
region参数格式为(left, top, width, height),通过right-left和bottom-top计算出准确的宽高。
内容的提问来源于stack exchange,提问作者Prado910
相关产品推荐
相关产品推荐

