Mac OSX11 (BigSur) 用AppleScript修改区域/国家(locale)的问题咨询
修复方案
问题原因
你的代码存在两处核心逻辑问题,导致弹窗操作失效:
- 执行顺序颠倒:在处理重启确认弹窗之前就调用了退出系统偏好设置的命令,此时弹窗依附的父窗口已经被销毁,无法定位到sheet窗口
- 交互逻辑不稳定:使用模拟tab+回车的操作依赖界面焦点状态,兼容性差,很容易因为焦点错位失效
修正后完整代码
property theSettings : {"", ""} set settings1 to {"Americas", "United States"} set settings2 to {"Europe", "Spain"} -- 先关闭已运行的系统偏好设置 if running of application "System Preferences" then try tell application "System Preferences" to quit on error do shell script "killall 'System Preferences'" end try delay 0.1 end if repeat while running of application "System Preferences" is true delay 0.1 end repeat -- 打开语言与地区设置页 tell application "System Preferences" reveal anchor "Language" of pane id "com.apple.Localization" activate end tell tell application "System Events" tell window "Language & Region" of process "System Preferences" -- 判断当前区域,切换目标配置 if (value of pop up button "Region:" of tab group 1) is "United States" then set theSettings to settings2 else set theSettings to settings1 end if set {theRegion, theCountry} to theSettings -- 选择区域和国家 tell pop up button "Region:" of tab group 1 delay 0.25 click delay 0.25 click menu item theRegion of menu 1 delay 0.25 click menu item theCountry of menu 1 of menu item theRegion of menu 1 end tell end tell delay 1 -- 先处理重启确认弹窗 if exists sheet 1 of window "Language & Region" of process "System Preferences" then tell sheet 1 of window "Language & Region" of process "System Preferences" activate -- 如果是中文系统,将按钮名替换为「不重启」即可 click button "Don't Restart" end tell end if delay 0.5 -- 处理完弹窗再退出系统偏好设置 tell application "System Preferences" to quit end tell
注意事项
运行脚本前需要给脚本运行的载体(脚本编辑器/自动操作/第三方脚本工具)开启辅助功能权限,权限入口在「系统设置→隐私与安全性→辅助功能」,勾选对应工具即可,否则系统事件的界面操作会被系统拦截。
内容的提问来源于stack exchange,提问作者Thierry Beliere
相关产品推荐
相关产品推荐

