Change LG UltraFine resolution through AppleScript

Solution 1:

Thanks to @wch1zpink and the suggestion to use the Watch Me Do option in Automator, here is a script that finally seems to do the job:

-- Portions of the script found on https://gist.github.com/mvaneijgen/2f48f859ca07d2e75b3a
-- Launch "System Preferences", open the "Displays" options and change to the "Display" tab
(* If error "System Events got an error: Script Editor is not allowed assistive access" appears, then System Preferences → Security & Privacy → Privacy → add Script Editor to "Allow the app to control your computer"*)
(* as per: https://stackoverflow.com/questions/31019916/is-not-allowed-for-assistive-access-error-when-running-applescript-from-java) *)

tell application "System Preferences"
    reveal anchor "displaysDisplayTab" of pane id "com.apple.preference.displays"
end tell

-- Now lets make the necessary changes
tell application "System Events"
    tell tab group 1 of window "LG UltraFine" of application process "System Preferences" of application "System Events"
        tell radio group 1

            if (value of radio button "Scaled") = 0 then -- Check if Scaled radio button is not selected
                click radio button "Scaled" -- Click the "Scaled" radio button

                -- and click on the icon above "Larger Text" (which is in fact a radio button)
                tell application "System Events"
                    tell tab group 1 of window "LG UltraFine" of application process "System Preferences" of application "System Events"
                        tell radio group 1 of group 2
                            click radio button 1
                        end tell
                    end tell
                end tell

                else -- Scaled radio button is already selected
                    click radio button "Default for display" -- therefore click on "Default for display"
            end if
        end tell
    end tell
end tell