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

使用Python自动化替换Keynote字体时,无法识别替换字体弹窗按钮的问题求助

自动化替换Keynote字体时,无法识别替换字体弹窗按钮的问题求助

我手动用Keynote的*Format > Font > Replace Fonts…*功能替换字体完全没问题,但想用Python+AppleScript自动化批量处理时卡壳了——代码能成功打开「替换字体」对话框,也能遍历列表里的字体行选择目标替换字体,但点击「Replace Fonts」按钮后,无法识别后续弹出的确认类弹窗按钮(比如询问是否替换所有字体实例的选项),导致脚本在这里卡死。

我已经试过各种方式调整AppleScript里的元素定位逻辑,甚至用Xcode的辅助功能检查工具去定位这个弹窗元素,但都没成功。我的需求很简单:让这个脚本能批量把不同语言文件夹里的Keynote/Numbers/Pages文件,统一替换成对应语言的指定字体(比如FR文件夹用「SF Hello」,CN用「SF Hello +SC」这类)。

以下是我的完整代码:

import os
import tkinter as tk
from tkinter import filedialog, messagebox
import subprocess

# Function to select the main folder
def select_folder():
    folder_path = filedialog.askdirectory()
    folder_entry.delete(0, tk.END)
    folder_entry.insert(0, folder_path)

# Function to execute the font replacement script
def execute_script():
    folder_path = folder_entry.get()
    if not os.path.isdir(folder_path):
        messagebox.showerror("Error", "Please select a valid folder.")
        return

    try:
        for root, dirs, files in os.walk(folder_path):
            for dir_name in dirs:
                if dir_name in ["FR", "CN", "JP", "KR", "BR"]:
                    language_folder = os.path.join(root, dir_name)
                    for sub_root, _, sub_files in os.walk(language_folder):
                        for file_name in sub_files:
                            if file_name.endswith(('.key', '.numbers', '.pages')):
                                file_path = os.path.join(sub_root, file_name)
                                replace_fonts(file_path, dir_name)
        messagebox.showinfo("Success", "Font replacement completed successfully.")
    except Exception as e:
        messagebox.showerror("Error", f"An error occurred: {str(e)}")

# Function to replace fonts using AppleScript
def replace_fonts(file_path, folder_name):
    font_mapping = {
        "FR": "SF Hello",
        "CN": "SF Hello +SC",
        "JP": "SF Hello +JP",
        "KR": "SF Hello +KR",
        "BR": "SF Hello"
    }
    target_font = font_mapping.get(folder_name, "SF Hello")

    # Escape file path for AppleScript
    escaped_file_path = file_path.replace('"', '\\"')

    applescript_code = f'''
    tell application "Finder"
        open POSIX file "{escaped_file_path}"
    end tell
    delay 3
    tell application "System Events"
        tell process "Keynote"
            -- Open Replace Fonts dialog
            click menu item "Replace Fonts…" of menu "Font" of menu item "Font" of menu "Format" of menu bar item "Format" of menu bar 1
            delay 3

            -- Access the Replace Fonts dialog
            set fontDialog to sheet 1 of window 1
            set fontTable to table 1 of scroll area 1 of fontDialog
            set rowCount to count of rows of fontTable

            -- Iterate through each row and replace fonts
            repeat with i from 1 to rowCount
                set fontRow to row i of fontTable
                set popUpButton to pop up button of fontRow -- Usually the second pop-up is the replacement target
                click popUpButton
                delay 1
                click menu item "{target_font}" of menu 1 of popUpButton
                delay 1
            end repeat

            -- Confirm the replacements
            click button "Replace Fonts" of fontDialog
        end tell
    end tell
    delay 3
    tell application "Keynote"
        save front document
        close front document
    end tell
    '''

    # Run the AppleScript using subprocess
    result = subprocess.run(["osascript", "-e", applescript_code], text=True, capture_output=True)
    if result.returncode != 0:
        raise RuntimeError(f"AppleScript error: {result.stderr}")


# Create the main UI window
root = tk.Tk()
root.title("Font Replacement Script")

# UI Elements
frame = tk.Frame(root)
frame.pack(padx=10, pady=10)

folder_label = tk.Label(frame, text="Select Main Folder:")
folder_label.grid(row=0, column=0, pady=5)

folder_entry = tk.Entry(frame, width=50)
folder_entry.grid(row=0, column=1, pady=5)

browse_button = tk.Button(frame, text="Browse", command=select_folder)
browse_button.grid(row=0, column=2, padx=5)

execute_button = tk.Button(frame, text="Execute", command=execute_script)
execute_button.grid(row=1, column=0, columnspan=3, pady=10)

# Run the main loop
root.mainloop()

我实在不知道该怎么定位这个弹出的确认按钮了,有没有大佬能帮我看看问题出在哪?或者有没有其他方式能绕过这个弹窗直接完成批量替换?

备注:内容来源于stack exchange,提问作者John Snow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 03:19:53