杰瑞科技汇

Python如何用GetWindowText获取窗口文本?

Of course! Getting the window text in Python is a common task for GUI automation, testing, or scraping. The best tool for this job is the pywin32 library, which provides a Python interface to the Microsoft Windows COM (Component Object Model) and Win32 API.

Python如何用GetWindowText获取窗口文本?-图1
(图片来源网络,侵删)

Here's a complete guide on how to get window text in Python, from basic usage to more advanced scenarios.

Prerequisites: Install pywin32

First, you need to install the necessary library. Open your command prompt or terminal and run:

pip install pywin32

The Core Concept: win32gui and EnumWindows

The process involves two main steps:

  1. Find the window(s) you're interested in. Windows provides a function EnumWindows that calls a callback function for every top-level window.
  2. Get the text of that window using the GetWindowText function.

The pywin32 library exposes these as win32gui.EnumWindows and win32gui.GetWindowText.

Python如何用GetWindowText获取窗口文本?-图2
(图片来源网络,侵删)

Example 1: Getting the Text of a Specific Window (by Title)

This is the most common use case. Let's say you want to get the title of the "Calculator" application.

We will iterate through all windows, check if the window title contains "Calculator", and if so, print its text.

import win32gui
import time
def get_window_text_by_title_partial(partial_title):
    """
    Finds a window with a title containing the partial_title string
    and returns its full window text.
    """
    def callback(hwnd, extra_list):
        if win32gui.IsWindowVisible(hwnd):
            window_title = win32gui.GetWindowText(hwnd)
            if partial_title.lower() in window_title.lower():
                extra_list.append(window_title)
    window_titles = []
    win32gui.EnumWindows(callback, window_titles)
    return window_titles[0] if window_titles else None
# --- Main execution ---
if __name__ == "__main__":
    # Give the user time to open the Calculator app
    print("Please open the Calculator application. Waiting for 5 seconds...")
    time.sleep(5)
    target_title = "Calculator"
    full_text = get_window_text_by_title_partial(target_title)
    if full_text:
        print(f"Found window with title containing '{target_title}'")
        print(f"Full window text: '{full_text}'")
    else:
        print(f"Could not find a window with title containing '{target_title}'")

How to run this:

  1. Save the code as a Python file (e.g., get_text.py).
  2. Open the Calculator app on your Windows machine.
  3. Run the script from your terminal: python get_text.py

Expected Output:

Please open the Calculator application. Waiting for 5 seconds...
Found window with title containing 'Calculator'
Full window text: 'Calculator'

Example 2: Getting Text from All Visible Windows

This script demonstrates how to iterate through all visible windows and print their titles. It's a great way to see what's available on your system.

import win32gui
def print_all_visible_window_titles():
    """
    Enumerates all visible top-level windows and prints their titles.
    """
    def callback(hwnd, extra_list):
        # We only care about visible windows
        if win32gui.IsWindowVisible(hwnd):
            window_title = win32gui.GetWindowText(hwnd)
            # We only want windows that have a title
            if window_title:
                extra_list.append(window_title)
    window_titles = []
    # EnumWindows calls the 'callback' function for each window, passing the
    # window handle (hwnd) and our list.
    win32gui.EnumWindows(callback, window_titles)
    print(f"Found {len(window_titles)} visible windows with titles:\n")
    for title in sorted(window_titles):
        print(f"- {title}")
# --- Main execution ---
if __name__ == "__main__":
    print_all_visible_window_titles()

Advanced: Getting Text from Controls Inside a Window

Sometimes you need the text from a button, a text box, or a label inside a window (e.g., getting the current result from the Calculator display). For this, you need to use win32gui's child window enumeration functions.

Python如何用GetWindowText获取窗口文本?-图3
(图片来源网络,侵删)

This is more complex because you have to first find the parent window and then find the specific child control within it.

Example: Getting the Text from the Calculator's Display

The Calculator's display is a static text control (STATIC class). We'll find it by its class name.

import win32gui
import win32con
import time
def get_child_window_text(parent_hwnd, child_class_name):
    """
    Finds a child window by its class name and returns its text.
    """
    child_hwnd = win32gui.FindWindowEx(parent_hwnd, 0, child_class_name, None)
    if child_hwnd:
        return win32gui.GetWindowText(child_hwnd)
    return None
def find_calculator_and_get_display_text():
    """
    Finds the Calculator window, then finds its display control and gets its text.
    """
    # First, find the main Calculator window
    def find_calculator_hwnd(hwnd, extra_list):
        if win32gui.IsWindowVisible(hwnd):
            window_title = win32gui.GetWindowText(hwnd)
            if "Calculator" in window_title:
                # Found it, add the window handle to our list
                extra_list.append(hwnd)
    calculator_hwnd_list = []
    win32gui.EnumWindows(find_calculator_hwnd, calculator_hwnd_list)
    if not calculator_hwnd_list:
        print("Calculator window not found.")
        return
    calculator_hwnd = calculator_hwnd_list[0]
    print(f"Found Calculator window with handle: {calculator_hwnd}")
    # The display in the Calculator is a 'STATIC' control
    display_text = get_child_window_text(calculator_hwnd, "STATIC")
    if display_text:
        print(f"Calculator display text: '{display_text}'")
    else:
        print("Could not find the display control (STATIC).")
# --- Main execution ---
if __name__ == "__main__":
    print("Please open the Calculator application. Waiting for 5 seconds...")
    time.sleep(5)
    find_calculator_and_get_display_text()

How to use this:

  1. Open Calculator.
  2. Type in a number, for example, 123 + 456.
  3. Run the script.
  4. It will first find the Calculator window, then find the STATIC control inside it (the display), and print its current content.

Expected Output:

Please open the Calculator application. Waiting for 5 seconds...
Found Calculator window with handle: 12345678
Calculator display text: '579'

Summary of Key win32gui Functions

Function Description
win32gui.EnumWindows(callback, list) Calls a function for every top-level window. Passes the window handle (hwnd) and your list to the callback.
win32gui.GetWindowText(hwnd) Returns the visible title text of the window with the given handle.
win32gui.IsWindowVisible(hwnd) Checks if the window is visible (not hidden or minimized).
win32gui.FindWindowEx(parent_hwnd, child_after, class_name, window_name) Finds a child window. Use parent_hwnd=0 to search top-level windows. Use class_name or window_name to filter.
win32gui.GetClassName(hwnd) Gets the class name of a window (e.g., "Notepad", "STATIC", "Button"). Useful for identifying controls.
分享:
扫描分享到社交APP
上一篇
下一篇