Code snippet works in isolation but not when embedded(fill text field)

The Applescript below is meant to do the following : Ask the Skitch app to take a screenshot (with the same parameters as the preceding screenshot, so it is assumed that a dummy screenshot has been made before), and save the screenshot on some location.


tell application "System Events"
	tell process "Skitch"
		set frontmost to true
		keystroke "5" using {command down, shift down, option down} (* Shortcut for `take screenshot`  *)
		keystroke "e" using {command down} (* Shortcut for `save`  *)
		set value of text field 1 of sheet 1 of window 1 to "my_saved_screenshot" 
	end tell
	key code 36
end tell

The code does not works as expected : the filename does not get written in the text field, the file is not saved, and I get the error “System Events got an error: Can’t get text field 1 of sheet 1 of window 1 of process "Skitch". Invalid index.” number -1719 from text field 1 of sheet 1 of window 1 of process “Skitch”.

What is suprising is that if I isolate the offending snippet and put in a new script, it works fine : a file is created with the correct name if I do the follwing after have made the screenshot separately :

tell application "System Events"
	tell process "Skitch"
		set frontmost to true
		keystroke "e" using {command down} (* Shortcut for `save`  *)
		set value of text field 1 of sheet 1 of window 1 to "my_saved_screenshot"
	end tell
	key code 36
end tell

What is going on here ? It seems that the variable sheet 1 of window 1 does not have the same value in the two situations.

Model: MacBook Air
AppleScript: 2.7
Browser: Safari 605.1.15
Operating System: macOS 10.14

Worked for me, thanks.
Since I intend to eventually put this in a loop, I’m tempted to use smaller values with delay … but from what I read, using delay with small fractions of a second is unsafe and not recommended

Fractional delays seem to work fine in most circumstances. The following is from the discussion of the delay command in the AppleScript Language Guide:

https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-DontLinkElementID_714