Change macOS background picture with "adapt to screen" parameter in python

221 views Asked by At

I want to change my wallpaper using python on macOs. Using this code :

from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File(file_loc))

which works fine, except it always resets parameter from "adjust to screen" to "centered". I can't find anything on how to add the "adjust to screen" parameter. Thanks for your help.

1

There are 1 answers

0
Ted Wrigley On

It's been a while since I've played with python, but I think I got something cobbled together. it uses PyObjC. PyObjC is installed with the most recent OS versions, but you may need to install it yourself if you're behind a few revisions. Basically this script calls NSWorkspace's setDesktopImageURL:forScreen:options:error: method with the NSImageScaleProportionallyUpOrDown option, and sets a dark gray color fill as a border.

I don't know the best way to get imagePath — sorry, my python is rusty, and I used a hard-coded value for testing — but it should be a POSIX file path.

from AppKit import NSWorkspace
from AppKit import NSScreen
from AppKit import NSColor

from AppKit import NSWorkspaceDesktopImageScalingKey
from AppKit import NSWorkspaceDesktopImageFillColorKey
from AppKit import NSImageScaleProportionallyUpOrDown

from Foundation import NSURL
from Foundation import NSDictionary

imageURL = NSURL.fileURLWithPath_(imagePath);
sharedSpace = NSWorkspace.sharedWorkspace();
mainScreen = NSScreen.mainScreen();
fillColor = NSColor.darkGrayColor();

optDict = NSDictionary.dictionaryWithObjects_forKeys_([NSImageScaleProportionallyUpOrDown, fillColor], [NSWorkspaceDesktopImageScalingKey,NSWorkspaceDesktopImageFillColorKey]);

sharedSpace.setDesktopImageURL_forScreen_options_error_(imageURL, mainScreen, optDict, None);

The scaling options available are:

  • NSImageScaleNone (do not adjust image size)
  • NSImageScaleAxesIndependently (fill the screen, stretching as needed)
  • NSImageScaleProportionallyUpOrDown (fit the screen on one axis, retaining aspect ratio)

See NSScreen if you need to wallpaper secondary monitors, and NSColor if you want to fill with a different color (has to be one of the predefined colors, or a custom color using RGB).

If you have difficulty making this work, or special concerns (like you need this to ship to computers that may not have PyObjC installed), these same NSWorkspace calls can be written in AppleScript, and then the AppleScript can be run from python using osascript. Let me know it that's a preferable solution.