Автоматизация замены шрифтов в Keynote с помощью Python. Я застрял и расстроен на этом этапеPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Автоматизация замены шрифтов в Keynote с помощью Python. Я застрял и расстроен на этом этапе

Сообщение Anonymous »

Я попробовал заменить все шрифты в Keynote, используя Format/fonts/replace font. Но автоматизируем это с помощью Python. Мой код работает до тех пор, пока не откроется диалоговое окно замены шрифта, но после этого он не может обнаружить всплывающую кнопку «Не заменять». Введите здесь описание изображения
Я не знаю, что еще сделать, чтобы выбрать эту опцию для всех этих шрифтов.

Код: Выделить всё

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()

Я пробовал выбрать элемент несколькими способами, но безуспешно. Также пробовал использовать параметр «Доступность» в Xcode, но ничего.
Я просто хочу, чтобы этот скрипт заменил все шрифты на один конкретный шрифт.

Подробнее здесь: https://stackoverflow.com/questions/793 ... strated-at
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»