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

MacOS Ventura/Monterey下带按钮的脚本选择AppleScript创建求助

AppleScript GUI按钮选择并执行脚本方案

用按钮式GUI替代列表选择

你可以用display dialog直接创建带3-9个按钮的界面,更贴合你的需求,完整示例代码如下:

-- 自定义按钮选项(可调整为3-9个)
set buttonChoices to {"Shell脚本1", "Shell脚本2", "AppleScript1", "AppleScript2"}

-- 弹出带按钮的选择对话框
try
    set chosenButton to button returned of (display dialog "选择要运行的脚本:" buttons buttonChoices default button 1)
on error number -128
    -- 用户取消操作,直接退出
    return
end try

-- 根据选择执行对应脚本
if chosenButton is "Shell脚本1" then
    -- 运行Shell脚本:替换为你的脚本绝对路径
    do shell script "/Users/yourname/scripts/script1.sh"
    -- 如果脚本需要管理员权限,加上这句:with administrator privileges
else if chosenButton is "Shell脚本2" then
    do shell script "/Users/yourname/scripts/script2.sh"
else if chosenButton is "AppleScript1" then
    -- 运行外部AppleScript文件
    run script file "/Users/yourname/scripts/script1.scpt"
else if chosenButton is "AppleScript2" then
    -- 直接执行AppleScript代码示例
    tell application "Finder"
        activate
        display dialog "AppleScript2已执行,Finder已激活"
    end tell
end if

改造你原有的列表选择代码

如果想保留原有的列表选择逻辑,只需在选择后添加执行判断即可:

set optionList to {"Shell Script-1", "Shell Script-2", "Applescript-1", "Applescript-2"}
set chosenScript to choose from list optionList with prompt "Choose a Script to run:"
if chosenScript is false then
    error number -128 (* User cancelled *)
else
    set chosenScript to chosenScript’s item 1 (* extract choice from list *)
    
    -- 新增执行逻辑,替换为你的脚本路径或代码
    if chosenScript is "Shell Script-1" then
        do shell script "/Users/yourname/scripts/shell1.sh"
    else if chosenScript is "Shell Script-2" then
        do shell script "/Users/yourname/scripts/shell2.sh"
    else if chosenScript is "Applescript-1" then
        run script file "/Users/yourname/scripts/apple1.scpt"
    else if chosenScript is "Applescript-2" then
        display dialog "Applescript-2执行成功"
    end if
end if

关键说明

  • 执行Shell脚本用do shell script命令,需传入脚本的绝对路径,如果需要权限可追加with administrator privileges
  • 执行AppleScript有两种方式:直接写代码逻辑,或用run script file "路径"调用外部.scpt文件
  • 路径注意用Mac的绝对路径格式,比如/Users/你的用户名/脚本存放目录/脚本名
  • 捕获错误码-128是处理用户取消操作的标准方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:45:27