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

pywin32的EnumWindows在Windows 10上间歇性抛出“找不到指定模块”错误的排查求助

pywin32的EnumWindows在Windows 10上间歇性抛出“找不到指定模块”错误的排查求助

我现在在Windows 10上写Python脚本,想要实现通过标题定位窗口,再用pywin32来移动和调整它的大小,写了下面的代码:

import win32gui

# Global variables
found_hwnd = None
partial_title = None  # We'll set this before calling EnumWindows

def enum_windows_callback(hwnd, lParam):
    global found_hwnd, partial_title
    if win32gui.IsWindowVisible(hwnd):
        window_title = win32gui.GetWindowText(hwnd)
        if partial_title and partial_title.lower() in window_title.lower():
            found_hwnd = hwnd
            # Returning False stops the enumeration
            return False
    # Continue enumerating
    return True

def find_window_by_title(title_substring):
    global found_hwnd, partial_title
    found_hwnd = None
    partial_title = title_substring
    win32gui.EnumWindows(enum_windows_callback, None)
    return found_hwnd

def move_and_resize_window(hwnd, x, y, width, height):
    if hwnd is None:
        print("No valid window handle provided.")
        return False
    win32gui.MoveWindow(hwnd, x, y, width, height, True)
    return True

if __name__ == "__main__":
    # Example usage:
    hwnd = find_window_by_title("Cha")

    if hwnd:
        print(f"Found window with HWND: {hwnd}")
        success = move_and_resize_window(hwnd, 100, 100, 800, 600)
        if success:
            print("Window moved and resized successfully.")
        else:
            print("Failed to move and resize the window.")
    else:
        print("No window found containing 'Notepad' in its title.")

但是运行这段代码时,有时候会弹出这个错误:

pywintypes.error: (126, 'EnumWindows', 'The specified module could not be found.')

这个问题很奇怪:当我查找一个不存在的窗口标题时,脚本会正常输出“未找到窗口”并退出;但当我查找某些确实存在的窗口时,就会触发这个错误。

我实在搞不懂原因,想请教各位:为什么pywin32的EnumWindows会间歇性抛出这个“找不到指定模块”(错误126)的问题?是不是我在环境配置、回调函数的写法,或者pywin32的安装过程中漏掉了什么?

以下是我已经尝试过的排查步骤:

  • 执行pip install --upgrade pywin32重新安装并升级了pywin32
  • 确保回调函数定义在脚本顶层,没有嵌套在其他函数里
  • 尝试以管理员身份运行脚本
  • 确认测试脚本和我的主脚本使用的是同一个Python解释器环境
  • 验证了pywin32和我的Python版本兼容(两者都是64位)

备注:内容来源于stack exchange,提问作者David Bandel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:29:33