0

I've been trying to randomize my wallpaper change with python by combining code from different sources. I managed to make this code:

import ctypes
import os
import random
drive = "C:/Users/UserName/Desktop/FolderofWallpaperFolders"
afolder = os.listdir(drive)
folder = drive+ "/" + random.choice(afolder)
aimage = os.listdir(folder)
image = random.choice(aimage)
image_path = os.path.join(drive, folder, image)
SPI_SETDESKWALLPAPER = 20 
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0,image_path, 3)

but when I run it it turns my wallpaper to a completely black screen. Any modification suggestions?

  • 1
    Possible duplicate of [Creating a background changer in python with ctypes, not working](https://stackoverflow.com/questions/21715895/creating-a-background-changer-in-python-with-ctypes-not-working) – Mike Scotty Jun 29 '17 at 12:14
  • Another duplicate: https://stackoverflow.com/questions/40574622/how-do-i-set-the-desktop-background-in-python-windows – Mike Scotty Jun 29 '17 at 12:16

1 Answers1

0

Problem

The major issue I see with your code is your use of the os.path.join() function. Look at the following four lines of your code:

drive = "C:/Users/UserName/Desktop/FolderofWallpaperFolders"
folder = drive+ "/" + random.choice(afolder)
image = random.choice(aimage)
image_path = os.path.join(drive, folder, image)

In your initialization of folder, you concatenate drive and a random folder's name. However, when you initialize image_path using os.path.join(), you concatenate drive, folder, and image into a single path that points to the location of an image. Or, at least, that's what it's supposed to do.

Unfortunately, because of the way you use os.path.join(), it returns an invalid directory and thus an invalid file. This is because folder already contains the string stored in drive, yet you're combining those two variables anyway with that function call. This is an example of what the path stored in image_path looks like right now:

"C:/Users/UserName/Desktop/FolderofWallpaperFolders/C:/Users/UserName/Desktop/FolderofWallpaperFolders/RandomlyChosenFolder/RandomlyChosenImage.jpg"

Solution

The simple solution is to change your image_path initialization to the following:

image_path = os.path.join(folder, image)

However, you may also want to consider your variable naming conventions. Your drive variable doesn't just store a string pointing to your drive, it stores a path to the folder FolderofWallpaperFolders. It may be worth it for you to go through your code and change some of your variable names or change what each variable is responsible for storing. Then carefully figure out how to use the os.path.join() function for your specific variables.

Xetnus
  • 353
  • 2
  • 4
  • 13