首页 > 解决方案 > 在 Python 3 中更改 Windows 10 背景

问题描述

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

标签: pythonpython-3.xwindowswindows-10ctypes

解决方案


对于 64 位窗口,请使用:

ctypes.windll.user32.SystemParametersInfoW

对于 32 位窗口,请使用:

ctypes.windll.user32.SystemParametersInfoA

如果你用错了,你会得到一个黑屏。您可以在Control Panel -> System and Security -> System中找到您使用的版本。

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

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 也更好地突出了这一点。


推荐阅读