Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Windows 10 background in Python 3

I've been trying to find the best way to change the Windows 10 Desktop wallpaper through a python script. When I try to run this script, the desktop background turns to a solid black color.

import ctypes

path = 'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'

def changeBG(path):
    SPI_SETDESKWALLPAPER = 20
    ctypes.windll.user32.SystemParametersInfoA(20, 0, path, 3)
    return;

changeBG(path)

What can I do to fix this? I'm using python3

like image 491
John Smith Avatar asked Dec 21 '18 02:12

John Smith


People also ask

How do you change the background color in python?

Right-click the upper-left corner of the Python console window and select Properties. In the dialog box that appears, pick the tab labeled Colors. On it you can set the screen background and text color. Save this answer.

How do I run a python background in Windows?

The easiest way of running a python script to run in the background is to use cronjob feature (in macOS and Linux). In windows, we can use Windows Task Scheduler. You can then give the path of your python script file to run at a specific time by giving the time particulars.

How do I run a program in the background in python?

import os pid = os. fork() if pid == 0: Continue to other code ... This will make the python process run in background. Save this answer.


1 Answers

For 64 bit windows, use:

ctypes.windll.user32.SystemParametersInfoW

for 32 bit windows, use:

ctypes.windll.user32.SystemParametersInfoA

If you use the wrong one, you will get a black screen. You can find out which version your using in Control Panel -> System and Security -> System.

You could also make your script choose the correct one:

import struct
import ctypes

PATH = 'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
SPI_SETDESKWALLPAPER = 20

def is_64bit_windows():
    """Check if 64 bit Windows OS"""
    return struct.calcsize('P') * 8 == 64

def changeBG(path):
    """Change background depending on bit size"""
    if is_64bit_windows():
        ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, PATH, 3)
    else:
        ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, PATH, 3)

changeBG(PATH)

Update:

I've made an oversight with the above. As @Mark Tolonen demonstrated in the comments, it depends on ANSI and UNICODE path strings, not the OS type.

If you use the byte strings paths, such as b'C:\\Users\\Patrick\\Desktop\\0200200220.jpg', use:

ctypes.windll.user32.SystemParametersInfoA

Otherwise you can use this for normal unicode paths:

ctypes.windll.user32.SystemParametersInfoW

This is also highlighted better with argtypes in @Mark Tolonen's answer, and this other answer.

like image 84
RoadRunner Avatar answered Oct 08 '22 06:10

RoadRunner