Applescript 将显示切换到灰度模式

Applescript to switch display to Greyscale mode

一直在尝试让 AppleScript 工作,将显示模式切换为灰度。

基于另一个几年前的脚本。 从那时起,Apple 更改了系统偏好设置面板的配置,从而破坏了脚本。

无法弄清楚如何让它导航到辅助功能面板中的 "Display" 菜单项。

tell application "System Preferences"
activate
reveal (pane id "com.apple.preference.universalaccess")
end tell


tell application "System Events"
    tell process "System Preferences"
        tell window "Accessibility"
            tell table 1 of scroll area 1
                delay 1
                select (row 4)
            end tell
            click checkbox "Use grayscale"
        end tell
    end tell
end tell
tell application "System Preferences" to quit

非常感谢任何帮助!

对于 macOS High Sierra,答案已在 this article 的评论中发布,因此请归功于原作者。

tell application "System Preferences"
    activate
    set the current pane to pane id "com.apple.preference.universalaccess"
    delay 1 # needs time to open universal access
    tell application "System Events" to tell process "System Preferences" to tell window "Accessibility"
        tell scroll area 2 to tell table 1 to tell row 6 #open display preferences

            select

        end tell

        click checkbox "Use grayscale"
    end tell
end tell

tell application "System Preferences" to quit

这在 macOS 10.13.5 中对我有用

如果您要编写 UI 脚本,请确保特定的 UI 元素在使用它们之前存在。最有效的方法是重复循环。

脚本选择名为 Display.

的行,而不是选择行号

如果脚本将在本地化环境中使用,请使用 AccessibilityDisplayUse grayscale

的本地化字符串
tell application "System Preferences"
    activate
    reveal pane id "com.apple.preference.universalaccess"
end tell

tell application "System Events"
    tell process "System Preferences"
        repeat until exists window "Accessibility"
            delay 0.1
        end repeat
        tell window "Accessibility"
            try
                select (first row of table 1 of scroll area 2 whose name of UI element 1 is "Display")
                click checkbox "Use grayscale"
            end try
        end tell
    end tell
end tell
quit application "System Preferences"

我要在这里加入第三个贡献,因为我承认我不喜欢到目前为止发布的两个脚本,尽管我完全同意@vadian 关于检查是否存在的建议。

我的第一个疑虑是没有必要 activate 系统偏好设置。它在后台运行得非常愉快,完全看不见。

我的第二点是,根本没有必要纠结必须 select 以及如何识别它的特定行:系统偏好设置 有,连同 panes,一系列 anchors,其中一个直接将您带到 "Display" 部分。

只有 一段UI 脚本,在这种情况下是一个令人遗憾的必需品,它是访问复选框并单击它。

您应该会发现下面脚本的结果更令人满意,因为 系统偏好设置 的作用在执行时似乎无法执行外观.

use prefs : application "System Preferences"
use sys : application "System Events"

property process : a reference to application process "System Preferences"
property window : a reference to window 1 of my process
property pane : a reference to pane id "com.apple.preference.universalaccess"
property anchor : a reference to anchor "Seeing_Display" of my pane
property checkbox : a reference to checkbox "Use grayscale" of my window

contents of my anchor = (reveal my anchor)
if the result = false then return

with timeout of 60 seconds
    repeat until my checkbox exists
        delay 0.5
    end repeat
end timeout

click my checkbox

quit prefs

系统信息: AppleScript 版本: "2.7", 系统版本:“10.13.6”