Windows 的背景桌面的更换是由 Windows API SystemParametersInfoW 提供的功能,Python 更换背景桌面通过调用 pywin32 来调用 Windows 的 API,实现更换背景桌面。
在使用前安装 pywin32 模块:
C:\Users\Administrator> pip install pywin32Collecting pywin32Downloading pywin32-304-cp38-cp38-win_amd64.whl (12.3 MB)---------------------------------------- 12.3/12.3 MB 1.5 MB/s eta 0:00:00Installing collected packages: pywin32Successfully installed pywin32-304
函数:
import ctypes, win32con# 获取当前背景桌面壁纸图片路径def getWallpaper():ubuf = ctypes.create_unicode_buffer(512)ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_GETDESKWALLPAPER, len(ubuf), ubuf, 0)return ubuf.value# 设置背景桌面为指定路径的图片def setWallpaper(path):changed = win32con.SPIF_UPDATEINIFILE | win32con.SPIF_SENDCHANGEctypes.windll.user32.SystemParametersInfoW(win32con.SPI_SETDESKWALLPAPER, 0, path, changed)
使用场景:

背景桌面的拉伸、居中效果是由注册表来控制的,与背景桌面的设置是分开的。设置背景桌面的拉伸效果的代码:
import win32api, win32con# mode_str 2:拉伸 0:居中 6:适应 10:填充 22:平铺def setWallpaperMode(mode_str):reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, mode_str)>>> setWallpaperMode('10')>>> setWallpaperMode('0')
参考:
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
https://splunktool.com/how-to-print-current-wallpaper-path-in-windows-10-using-python
全文完。
如果转发本文,文末务必注明:“转自微信公众号:生有可恋”。
文章转载自生有可恋,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




