在 Python 3 中更改 Windows 10 背景

Change Windows 10 background in Python 3

我一直在努力寻找通过 python 脚本更改 Windows 10 桌面墙纸的最佳方法。当我尝试 运行 这个脚本时,桌面背景变成纯黑色。

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)

我该怎么做才能解决这个问题?我正在使用 python3

对于 64 位 windows,使用:

ctypes.windll.user32.SystemParametersInfoW

对于 32 位 windows,使用:

ctypes.windll.user32.SystemParametersInfoA

如果用错了,会黑屏。您可以在 控制面板 -> 系统和安全 -> 系统.

中找到您使用的版本

您也可以让您的脚本选择正确的脚本:

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)

更新:

我对上面的内容进行了疏忽。正如 在评论中所展示的那样,它取决于 ANSI 和 UNICODE 路径字符串,而不是 OS 类型。

如果使用字节字符串路径,例如b'C:\Users\Patrick\Desktop\0200200220.jpg',请使用:

ctypes.windll.user32.SystemParametersInfoA

否则,您可以将其用于普通的 unicode 路径:

ctypes.windll.user32.SystemParametersInfoW

answer, and this other .

中的 argtypes 也更好地突出显示了这一点

SystemParametersInfoA 采用 ANSI 字符串(bytes 输入 Python 3)。

SystemParametersInfoW 采用 Unicode 字符串(str 输入 Python 3)。

所以使用:

path = b'C:\Users\Patrick\Desktop\0200200220.jpg'
ctypes.windll.user32.SystemParametersInfoA(20, 0, path, 3)

或:

path = 'C:\Users\Patrick\Desktop\0200200220.jpg'
ctypes.windll.user32.SystemParametersInfoW(20, 0, path, 3)

您可以设置argtypes来进行参数检查。第三个参数记录为 LPVOID 但您可以更具体地进行类型检查:

from ctypes import *
windll.user32.SystemParametersInfoW.argtypes = c_uint,c_uint,c_wchar_p,c_uint
windll.user32.SystemParametersInfoA.argtypes = c_uint,c_uint,c_char_p,c_uint