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

Mac系统下使用Python、Selenium设置窗口焦点并激活Photoshop的问题求助

报错原因

getWindowsWithTitle 是 pygetwindow、pyautogui 仅针对Windows平台实现的接口,macOS系统下未做适配,所以会抛出属性不存在的异常。

可行解决方案

方案1:调用系统内置AppleScript实现(无需额外安装依赖)

macOS自带AppleScript可直接控制应用窗口,通过Python的subprocess模块调用即可,不需要安装第三方库:

import subprocess
import platform

if platform == "darwin":
    # 直接激活Photoshop应用
    subprocess.run(["osascript", "-e", 'tell application "Photoshop" to activate'], check=True)

如果需要匹配具体的Photoshop文档窗口,可使用如下逻辑:

import subprocess
import platform

if platform == "darwin":
    target_window_name = "需要激活的文档名称"
    script = f'''
    tell application "System Events"
        tell process "Photoshop"
            set frontmost to true
            repeat with win in windows
                if name of win contains "{target_window_name}" then
                    perform action "AXRaise" of win
                    exit repeat
                end if
            end repeat
        end tell
    end tell
    '''
    subprocess.run(["osascript", "-e", script], check=True)

方案2:使用跨平台窗口控制库pywinctl

pywinctl 是跨平台的窗口控制库,完美兼容macOS,替代仅支持Windows的pygetwindow:

  1. 安装依赖:
    pip install pywinctl
  2. 激活Photoshop窗口代码:
import pywinctl as gw
import platform

if platform == "darwin":
    # 匹配所有标题包含Photoshop的窗口
    win_list = gw.getWindowsWithTitle("Photoshop")
    if win_list:
        # 激活第一个匹配到的窗口
        win_list[0].activate()

注意事项

macOS安全机制限制,控制第三方应用窗口需要先给运行Python的终端/IDE开启辅助功能权限:打开系统设置→隐私与安全性→辅助功能,勾选你使用的终端、IDE(如VSCode、IDLE等)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:39:02