You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Python截图工具:能否通过鼠标点击获取窗口坐标?

实现点击窗口获取坐标并截图(Windows平台)

完全可行,Windows平台下可以通过调用系统API实现这个功能,下面是具体的实现步骤和代码示例:

安装必要依赖

先安装pywin32(用于调用Windows原生API)和Pillow(用于截图与图片处理):

pip install pywin32 pillow

核心实现逻辑

  1. 触发窗口选择模式后,监听鼠标点击事件
  2. 通过鼠标点击位置获取对应窗口的句柄
  3. 利用窗口句柄获取窗口的边界坐标(左上、右下)
  4. 根据坐标截取对应区域的屏幕内容

完整代码示例

import tkinter as tk
import win32api
import win32gui
from PIL import ImageGrab, ImageTk

class ScreenshotApp:
    def __init__(self, root):
        self.root = root
        self.root.title("工作专用截图工具")
        self.root.geometry("320x120")
        
        # 窗口截图模式按钮
        self.window_btn = tk.Button(
            root, 
            text="选择窗口截图", 
            width=15,
            command=self.start_window_selection
        )
        self.window_btn.pack(pady=30)
        
        self.is_selecting = False

    def start_window_selection(self):
        self.is_selecting = True
        # 主窗口半透明,不遮挡目标窗口
        self.root.attributes("-alpha", 0.2)
        # 绑定鼠标左键点击事件
        self.root.bind("<Button-1>", self.capture_window)

    def capture_window(self, event):
        if not self.is_selecting:
            return
        
        # 获取鼠标点击的屏幕坐标
        cursor_x, cursor_y = win32api.GetCursorPos()
        # 获取坐标点对应的窗口句柄
        target_hwnd = win32gui.WindowFromPoint((cursor_x, cursor_y))
        
        # 排除自身Tkinter窗口
        if target_hwnd == self.root.winfo_id():
            return
        
        # 获取窗口的边界坐标 (left, top, right, bottom)
        left, top, right, bottom = win32gui.GetWindowRect(target_hwnd)
        # 截取窗口区域
        window_screenshot = ImageGrab.grab(bbox=(left, top, right, bottom))
        
        # 显示截图预览
        self.show_preview(window_screenshot)
        
        # 恢复主窗口状态
        self.is_selecting = False
        self.root.attributes("-alpha", 1.0)
        self.root.unbind("<Button-1>")

    def show_preview(self, img):
        # 新建窗口展示截图
        preview_win = tk.Toplevel(self.root)
        preview_win.title("截图预览")
        img_tk = ImageTk.PhotoImage(img)
        preview_label = tk.Label(preview_win, image=img_tk)
        preview_label.image = img_tk
        preview_label.pack(padx=10, pady=10)

if __name__ == "__main__":
    root = tk.Tk()
    app = ScreenshotApp(root)
    root.mainloop()

补充说明

  • 代码中使用的win32gui.WindowFromPoint和GetWindowRect是Windows原生API,能精准获取窗口的真实坐标,和系统自带截图工具的窗口识别逻辑一致
  • 如果遇到截图黑屏问题,尝试以管理员身份运行脚本(Windows系统权限限制)
  • 可以扩展功能:比如添加截图保存按钮、编辑工具等,和你已实现的拖拽截图功能整合

内容的提问来源于stack exchange,提问作者Mi5trB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:35:05