AppleScript Tutorial: Display Dialog and Returning Values

27 February 2009

This tutorial will show you how to inform the user of the AppleScript and also how to ask questions and use the information returned within your own AppleScript using a dialog.

This tutorial fundamentally describes the use of Dialog Boxes within AppleScript. For more information about Dialog Boxes, please refer to the AppleScript Language Guide in the reference section of this site.


Creating your first Dialog

To tell the user of your AppleScript that something has happened can be done very easily using the following code. This is the minimal amount of code required to display a dialog.

AppleScript Code:
display dialog "Finished"

This code simply displays the following dialog.

Dialog Options

There are many options that can be used with the Dialog and they include
  • Title (Adding a Title in the top grey bar of the above dialog box)
  • Icon (Adding a choice of 3 icons to left side of the Dialog
  • Input (Add a text box where the user can add in text)
  • Buttons (Can have up to 3 buttons)
Each of these options can be used independently


Returning Values through a Dialog

In this section, we are going to use some of the above options to create a dialog that checks if the user can add two numbers.

First, let’s just get the Dialog correct before we try to capture the returned values

AppleScript Code:
display dialog "What is 2 + 2?" default answer "8?" with icon 2 with title "Are you Smarter than a 3rd Grader"

The code above produces the following result

OK, now let’s capture the returned value and check if it is correct.
To capture the returned value we need to set the return value to a variable and we do this adding “Set Variable_Name” infront of the display dialog code above.

The dialog box will return more than one result so we also need to be specific about what result we wish to check. Follow the code below to see how it is done.

Example AppleScript Code:

set return_value to display dialog "What is 2 + 2?" default answer "8?" with icon 2 with title "Are you Smarter than a 3rd Grader"


set answer to text returned of return_value


if answer = "4" then

display dialog "Correct! Nice Work!" with icon 1

else

display dialog "Wrong!" with icon 0 buttons {"Done"} default button "Done"

end if

And that covers it. To download the complete AppleScript, click download AppleScript below. Download Example AppleScript



Reference Documents

To review the complete AppleScript Guide as well as other AppleScript Guides for MS Word, Excel, PowerPoint or Adobe Photoshop please review the “Reference Documents” page on this website.
AppleScript Reference Documents

Best of luck with your AppleScripting adventures.

Regards,

Thompson-Solutions