Script to toggle between fn keys (with Touchbar) I'm trying to write a script to toggle between Fn keys and app controls on the Touchbar using macOS High Sierra. There a few apps out there that say they can do it but none seem to work for Touchbar. So I'm now trying to write script that opens up the System Preferences, keyboard settings and toggling the Touch Bar setting. So far I have the code below which toggles "Adjust keyboard brightness in low light". I just need to adjust to select an option from the Touch Bar drop down menu. 

tell application "System Preferences"
    activate
    set the current pane to pane id "com.apple.preference.keyboard"
    reveal anchor "keyboardTab" of pane id "com.apple.preference.keyboard"
end tell

tell application "System Events" to tell process "System Preferences"
    click checkbox 1 of tab group 1 of window 1
end tell

quit application "System Preferences"
You can check the components of the UI interface of the application you're trying to script with the "UI elements" command

tell application "System Events"
    tell application process "System Preferences"
        get the UI elements of the window "Keyboard"
    end tell
end tell


you can then drill down the list to find where the required item is

tell application "System Events"
    tell application process "System Preferences"
        get the UI elements of tab group 1 of window "Keyboard"
    end tell
end tell


actually using the Accessibility Inspector app (part of Xcode) can help you to identify which element to inspect

For our purposes, it looks like the popup we are interested into is the
 pop up button 2 of tab group 1 of window "Keyboard"

Since it is a pop up, to interact with its menu, you have to click on it and then to select the item you want to activate. It can be done by specifying the whole label of the menu item to click, I preferred to simulate the keystrokes needed to switch the selection (either the up or down arrow and then the return)...

tell application "System Preferences"
    -- activate
    reveal anchor "keyboardTab" of pane id "com.apple.preference.keyboard"
end tell

delay 0.5 -- this depends on how fast is your mac

tell application "System Events"
    tell application process "System Preferences"
        set thePopup to pop up button 2 of tab group 1 of window "Keyboard"

        tell thePopup
            click
            delay 0.2

            if the value of thePopup begins with "App" or the value of thePopup begins with "Expanded" then
                key code {125, 125, 125, 36}
            else
                key code {126, 36}
            end if

        end tell

    end tell
end tell

quit application "System Preferences"


by the way, in another question, someone noticed that if you don't activate the System Preferences app, the scripts will still work but without showing its window (you will still see the popup menu being switched, though)