杰瑞科技汇

Python GetWindowRect如何获取窗口坐标?

Of course! In Python, getting the dimensions and position of a window is a common task for automation, GUI testing, or creating utility applications. The standard and most reliable way to do this is by using the pygetwindow library, which is a cross-platform wrapper around native OS APIs.

Python GetWindowRect如何获取窗口坐标?-图1
(图片来源网络,侵删)

Here’s a complete guide, from installation to usage and examples.

Installation

First, you need to install the pygetwindow library. It's available on PyPI, so you can use pip.

pip install pygetwindow

Basic Usage: getWindowsWithTitle()

The core function you'll use is pygetwindow.getWindowsWithTitle(). This function searches for all windows whose title matches the given string and returns a list of Window objects.

Key Point: Window titles often include the full path of the application (e.g., C:\Users\YourUser\Documents\my_file.txt - Notepad). It's best to search for a unique, partial string within the title.

Python GetWindowRect如何获取窗口坐标?-图2
(图片来源网络,侵删)

Example: Getting Notepad's Window

Let's find the Notepad window and get its rectangle.

import pygetwindow as gw
# Get a list of all windows with "Notepad" in the title
notepad_windows = gw.getWindowsWithTitle('Notepad')
if notepad_windows:
    # We take the first window from the list
    notepad_win = notepad_windows[0]
    # Get the rectangle object
    rect = notepad_win.left, notepad_win.top, notepad_win.right, notepad_win.bottom
    print(f"Window Title: '{notepad_win.title}'")
    print(f"Window Rectangle (left, top, right, bottom): {rect}")
    # You can also get width and height directly
    print(f"Width: {notepad_win.width}")
    print(f"Height: {notepad_win.height}")
    print(f"Position (left, top): ({notepad_win.left}, {notepad_win.top})")
else:
    print("No Notepad window found. Please open Notepad and run the script again.")

Example Output:

Window Title: 'C:\Users\YourUser\AppData\Local\Temp\test.txt - Notepad'
Window Rectangle (left, top, right, bottom): (100, 100, 700, 500)
Width: 600
Height: 400
Position (left, top): (100, 100)

The Window Object and its Properties

Once you have a Window object, you can access several useful properties and methods.

| Property / Method | Description | Example | | :--- | :--- | :--- | | The full title of the window. | win.title | | left | The x-coordinate of the left edge of the window. | win.left | | top | The y-coordinate of the top edge of the window. | win.top | | right | The x-coordinate of the right edge of the window. | win.right | | bottom | The y-coordinate of the bottom edge of the window. | win.bottom | | width | The width of the window. | win.width | | height | The height of the window. | win.height | | topleft | A tuple (left, top) representing the top-left corner. | win.topleft | | size | A tuple (width, height) representing the window size. | win.size | | isActive | True if the window is the currently active (focused) window. | win.isActive | | isMinimized | True if the window is minimized. | win.isMinimized | | isMaximized | True if the window is maximized. | win.isMaximized | | isVisible | True if the window is visible on the screen. | win.isVisible | | activate() | Brings the window to the foreground and activates it. | win.activate() | | maximize() | Maximizes the window. | win.maximize() | | minimize() | Minimizes the window. | win.minimize() | | restore() | Restores the window from a minimized or maximized state. | win.restore() | | close()** | Closes the window. | win.close() |


Complete Example: Finding and Resizing a Window

This script will find your web browser (assuming it's open and has "Google Chrome" or "Mozilla Firefox" in the title), print its current position and size, and then resize it.

Python GetWindowRect如何获取窗口坐标?-图3
(图片来源网络,侵删)
import pygetwindow as gw
import time
def find_and_resize_browser():
    """
    Finds a browser window, prints its details, and resizes it.
    """
    # Try to find Chrome or Firefox
    browser_windows = gw.getWindowsWithTitle('Google Chrome') or gw.getWindowsWithTitle('Mozilla Firefox')
    if not browser_windows:
        print("Could not find a browser window. Please open Chrome or Firefox.")
        return
    browser_win = browser_windows[0]
    print(f"Found window: '{browser_win.title}'")
    print("--- Before Resize ---")
    print(f"  Position: ({browser_win.left}, {browser_win.top})")
    print(f"  Size: {browser_win.width} x {browser_win.height}")
    print("-" * 20)
    # Resize the window
    new_width = 800
    new_height = 600
    browser_win.size = (new_width, new_height)
    # Optional: Move the window to a specific position
    new_left = 50
    new_top = 50
    browser_win.topleft = (new_left, new_top)
    print("--- After Resize ---")
    print(f"  New Position: ({browser_win.left}, {browser_win.top})")
    print(f"  New Size: {browser_win.width} x {browser_win.height}")
    print("-" * 20)
    # Wait a bit so you can see the change
    time.sleep(5)
    # Restore the window to its original state (optional)
    # browser_win.restore() # In case it was maximized
    # browser_win.size = (original_width, original_height)
    # browser_win.topleft = (original_left, original_top)
    print("Script finished. You can manually restore your browser window.")
if __name__ == "__main__":
    find_and_resize_browser()

Alternative: Using pywin32 (Windows Only)

If you are only working on Windows and need more low-level control, you can use pywin32. This library gives you direct access to the Windows API. It's more complex but can be more powerful in specific scenarios.

Installation:

pip install pywin32

Example with pywin32:

import win32gui
import win32con
def get_window_rect_win32(window_title):
    """
    Gets the rectangle of a window by its title using pywin32.
    Returns a tuple (left, top, right, bottom) or None if not found.
    """
    def callback(hwnd, extra):
        if window_title in win32gui.GetWindowText(hwnd):
            rect = win32gui.GetWindowRect(hwnd)
            # The callback stops when we find the first match
            win32gui.EnumWindows(lambda x, y: False, None) # Stop enumeration
            return rect
        return None
    # Enumerate all top-level windows
    hwnd = win32gui.FindWindow(None, window_title) # Exact match
    if not hwnd:
        # Fallback to partial match by enumerating
        rect = win32gui.EnumWindows(callback, None)
        return rect
    else:
        return win32gui.GetWindowRect(hwnd)
# --- Usage ---
notepad_rect = get_window_rect_win32("Notepad")
if notepad_rect:
    print(f"Found Notepad window using pywin32: {notepad_rect}")
    # rect is a tuple: (left, top, right, bottom)
    left, top, right, bottom = notepad_rect
    width = right - left
    height = bottom - top
    print(f"Width: {width}, Height: {height}")
else:
    print("Notepad window not found.")

Summary: pygetwindow vs. pywin32

Feature pygetwindow pywin32
Simplicity Excellent. Very high-level, easy to use. Complex. Requires knowledge of Windows API concepts.
Cross-Platform Yes. Works on Windows, macOS, and Linux. No. Windows only.
Dependencies Minimal. Requires the full pywin32 installation.
Use Case Ideal for most automation tasks, quick scripts, and GUI testing. Best for advanced Windows-specific automation where you need fine-grained control.

For 99

分享:
扫描分享到社交APP
上一篇
下一篇