GLHF
GLHF

Reputation: 4054

Python 3.4 changing desktop background image does not work

I tried every example on SO and Google, but none of them working. I don't know why, script finishes without any error. But background image does not changing. I put absolute path for that image, I tried jpg,png formats, basically I tried everything but all examples finished without any error and yet background image doesn't changed. Is there a working example for this? Windows-7 Python 3.4

Some examples didn't work;

import ctypes
SPI_SETDESKWALLPAPER = 20 
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "myimage.jpg" , 0)
########################################

#This example can't find images, but I put absolute path to it. Don't know what's the problem
import struct
import ctypes


SPI_SETDESKWALLPAPER = 20
WALLPAPER_PATH = 'C:\\your_file_name.jpg'


def is_64_windows():
    """Find out how many bits is OS. """
    return struct.calcsize('P') * 8 == 64


def get_sys_parameters_info():
    """Based on if this is 32bit or 64bit returns correct version of SystemParametersInfo function. """
    return ctypes.windll.user32.SystemParametersInfoW if is_64_windows() \
        else ctypes.windll.user32.SystemParametersInfoA


def change_wallpaper():
    sys_parameters_info = get_sys_parameters_info()
    r = sys_parameters_info(SPI_SETDESKWALLPAPER, 0, WALLPAPER_PATH, 3)

    # When the SPI_SETDESKWALLPAPER flag is used,
    # SystemParametersInfo returns TRUE
    # unless there is an error (like when the specified file doesn't exist).
    if not r:
        print(ctypes.WinError())


change_wallpaper()

Upvotes: 0

Views: 724

Answers (1)

ands
ands

Reputation: 2046

try using following code:

import struct
import ctypes
import os

def is_64_windows():
    """Find out how many bits is OS. """
    return 'PROGRAMFILES(X86)' in os.environ

def get_sys_parameters_info():
    """Based on if this is 32bit or 64bit returns correct version of SystemParametersInfo function. """
    return ctypes.windll.user32.SystemParametersInfoW if is_64_windows() \
        else ctypes.windll.user32.SystemParametersInfoA

def change_wallpaper():
    sys_parameters_info = get_sys_parameters_info()
    r = sys_parameters_info(SPI_SETDESKWALLPAPER, 0, WALLPAPER_PATH, 3)
    if not r:           # When the SPI_SETDESKWALLPAPER flag is used, SystemParametersInfo returns TRUE unless there is an error (like when the specified file doesn't exist).
        print(ctypes.WinError())

SPI_SETDESKWALLPAPER = 20
WALLPAPER_PATH = 'C:\\your_file_name.jpg'
change_wallpaper()

I think your problem is that you have 64 windows but 32 python, a then your is_64_windows() function returns False but it is actually True, 'PROGRAMFILES(X86)' in os.environ should work.

Upvotes: 1

Related Questions