JimenezLi

JimenezLi

Average Minecraft Modder
github

Automatically Edit Desktop Wallpaper on Windows

I want to write a program that adds an xkcd comic to the desktop wallpaper every day. So I did the following series of things and successfully implemented the functionality.

Writing Python Script#

Using web crawler to get xkcd comics#

The structure of the xkcd website is relatively simple, just need to find the comic image link in the HTML. Use the following code:

url = 'https://xkcd.com/'

try:
    # Use the requests library to get the webpage
    r = requests.get(url)
    r.raise_for_status()
    r.encoding = r.apparent_encoding

    # Use bs4.BeautifulSoup to parse HTML
    soup = BeautifulSoup(r.text, 'lxml')
    imgs = soup.find_all('img')

    # Find the xkcd comic link among the image links
    for i in imgs:
        src = str(i.get('src'))
        if '/comics/' in src:
            if src.startswith('//'):
                src = 'https:' + src

            # Get and save the comic image
            imgfile = requests.get(src)
            imgfile.raise_for_status()
            with open('./resources/xkcd.jpg', 'wb') as f:
                f.write(imgfile.content)
                f.close()
            print('Get xkcd image success')
            break
    else:
        raise Exception(f'No comic found in {url}')

# Save exception information when an exception occurs
except Exception as e:
    print('Get xkcd image fail')
    with open(f'crash.log', 'a') as f:
        # current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f'[{current_date}]:', e, file=f)
        f.close()

Editing wallpaper using PIL image processing library#

Other image processing libraries like OpenCV can also be used.

# Open background
wallpaper = Image.open('./resources/background.jpg')

# Open xkcd image
xkcd = Image.open('./resources/xkcd.jpg')
wallpaper_xkcd = xkcd.resize((2 * xkcd.width, 2 * xkcd.height)).convert('RGB')
# Here I set the xkcd comic to the top right corner of the wallpaper
wallpaper.paste(wallpaper_xkcd, box=(wallpaper.width * 15 // 16 - wallpaper_xkcd.width, wallpaper.height // 16))

# Save to wallpaper
with open('./wallpaper.jpg', 'wb') as f:
    wallpaper.save(f)
    f.close()

Changing wallpaper using Windows API#

It was difficult for me to find the required Windows API, so I asked for help from 文心一言. ChatGPT can also be used.

win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, os.path.join(script_path, 'wallpaper.jpg'))

The preview effect is shown in the following image, where an xkcd comic is added to the top right corner of the wallpaper.
wallpaper.jpg

Adding the script to Windows task#

After the program is set up, it needs to be added to Windows task in order to execute it regularly.
Use the search function of Windows (shortcut: Windows+Q) to find "Task Scheduler". Click "Create Task" in the "Actions" on the right to set it up. The specific settings can be found in the reference materials under "windows 定时运行 exe 文件" (how to schedule the execution of an exe file in Windows).
Task Scheduler

Set the trigger#

Be sure to set the trigger, otherwise the task won't know when to execute. I set it to run every day at 23:00.
Trigger

Set the parameters for the action#

  • Program/script: If your system has Python installed, you can write python in the "Program/script" field, or you can write the path to python.exe.
  • Add arguments: Only need to write the path to the script in "Add arguments". (Actually, you can write everything in the "Program/script" field, the system will automatically separate the arguments)
  • Start in: Must be written, otherwise the program may not execute correctly. Set this parameter to the path of the script.

This way, automatic editing of the desktop wallpaper in Windows is achieved.

Reference materials#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.