在Python 3中更改Windows 10的背景

6

我一直在尝试通过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。

2个回答

8

对于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)

更新:

我在上面犯了一个错误。正如@Mark Tolonen在评论中展示的那样,它取决于ANSI和UNICODE路径字符串,而不是操作系统类型。

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

ctypes.windll.user32.SystemParametersInfoA

否则,您可以使用此选项来处理普通的Unicode路径:
ctypes.windll.user32.SystemParametersInfoW

@Mark Tolonen的答案中,使用argtypes更好地突出了这一点,另外还有这个答案


2
真正的问题不在于定义argtypes。A版本使用字节字符串作为第三个参数,而W版本使用Unicode字符串。只要正确调用它们,无论操作系统类型,都可以同时使用A和W。 - Mark Tolonen

3

SystemParametersInfoA接受ANSI字符串(在Python 3中为bytes类型)。

SystemParametersInfoW接受Unicode字符串(在Python 3中为str类型)。

因此,请使用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接