python代码的截图占用了比它应该占用的更多像素

  • 本文关键字:像素 代码 python 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")

我已经尝试过从不同的窗口和附加像素总是变化的

Test 1测试2测试3

win32gui.GetWindowRect的输出与pyautogui.screenshot的输入不一致:

  • win32gui元组由(左,上,右,下)
  • pyautogui元组由(left, top,widthheight)

因此,不能直接使用window_region作为参数,而是先转换它:

#[...]
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
left, top, right, bottom = window_region
screenshot_region = (left, top, right - left, bottom - top)
pg.screenshot(file, region=screenshot_region)
#[...]

注:这将仍然包含窗口的投影,所以它可能看起来"有点太大"。要获得没有阴影的窗口坐标,您可以使用DwmGetWindowAttribute,参见https://stackoverflow.com/a/54770938/9501624示例。

最新更新