leo.blog();

Change KDE wallpaper from the command line

Here’s how you can programmatically change your wallpaper in KDE.

You need to execute the following script inside the Plasma Shell.

desktops().forEach(d => {
  d.currentConfigGroup = Array(
    "Wallpaper",
    "org.kde.image",
    "General");
  d.writeConfig("Image", "file://[FILE_PATH]");
  d.reloadConfig();
});

You can construct this as a string, replace [FILE_PATH] with the path to the image file, and then send a d-bus message to the Plasma Shell. For this, I use the following command.

qdbus6 org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell.evaluateScript $scriptText

Python script

Here’s a Python script that downloads a random Anime picture and sets it as wallpaper.

#!/usr/bin/env python
import requests
import subprocess
from pathlib import Path
import tempfile

def set_wallpaper(p: Path):
    p = p.resolve()

    script = """
    desktops().forEach(d => {
        d.currentConfigGroup = Array("Wallpaper",
                                     "org.kde.image",
                                     "General");
        d.writeConfig("Image", "file://FILEPATH");
        d.reloadConfig();
    });
    """.replace("FILEPATH", str(p))

    cmd = [
        "qdbus6",
        "org.kde.plasmashell",
        "/PlasmaShell",
        "org.kde.PlasmaShell.evaluateScript",
        script,
    ]

    subprocess.check_call(cmd, stdout=subprocess.DEVNULL)


def main():
    with tempfile.NamedTemporaryFile() as f:
        p = Path(f.name).resolve()
        url = "https://pic.re/image"
        p.write_bytes(requests.get(url).content)
        set_wallpaper(p)


if __name__ == "__main__":
    main()

Leave a Comment