如何用Python为Windows特定显示器设置桌面壁纸?
为特定显示器单独设置壁纸的Python实现
要实现像系统菜单那样为单台显示器设置壁纸,不能用SystemParametersInfoW(它只能全局设置),需要调用Windows 10 1607及以上版本提供的SetWallpaperForMonitor API,结合显示器枚举来定位目标屏幕。
实现步骤
- 枚举系统中所有显示器,获取每台显示器的设备标识符(
szDevice)。 - 调用
SetWallpaperForMonitor为指定显示器设置壁纸。
完整代码示例
import os import ctypes from ctypes import wintypes # 加载所需Windows系统库 user32 = ctypes.WinDLL('user32', use_last_error=True) shcore = ctypes.WinDLL('shcore', use_last_error=True) # 定义存储显示器信息的结构体 class MONITORINFOEXW(ctypes.Structure): _fields_ = [ ('cbSize', wintypes.DWORD), ('rcMonitor', wintypes.RECT), ('rcWork', wintypes.RECT), ('dwFlags', wintypes.DWORD), ('szDevice', wintypes.WCHAR * 32) ] # 定义枚举显示器的回调函数类型 MONITORENUMPROC = ctypes.WINFUNCTYPE( wintypes.BOOL, wintypes.HMONITOR, wintypes.HDC, wintypes.LPRECT, wintypes.LPARAM ) # 获取所有显示器的设备名称列表 def get_monitor_devices(): devices = [] def callback(hMonitor, hdcMonitor, lprcMonitor, dwData): info = MONITORINFOEXW() info.cbSize = ctypes.sizeof(MONITORINFOEXW) if user32.GetMonitorInfoW(hMonitor, ctypes.byref(info)): devices.append(info.szDevice) return True user32.EnumDisplayMonitors(None, None, MONITORENUMPROC(callback), 0) return devices # 绑定SetWallpaperForMonitor API并定义参数类型 SetWallpaperForMonitor = shcore.SetWallpaperForMonitor SetWallpaperForMonitor.argtypes = [ wintypes.LPCWSTR, # 目标显示器设备名称 wintypes.LPCWSTR, # 壁纸文件绝对路径 wintypes.LPCWSTR, # 壁纸样式(留空用系统默认) wintypes.LPCWSTR # 扩展选项(留空即可) ] SetWallpaperForMonitor.restype = wintypes.HRESULT # 为指定显示器设置壁纸的封装函数 def set_monitor_wallpaper(monitor_device, wallpaper_path): abs_path = os.path.abspath(wallpaper_path) if not os.path.exists(abs_path): raise FileNotFoundError(f"壁纸文件不存在:{abs_path}") result = SetWallpaperForMonitor(monitor_device, abs_path, None, None) if result != 0: raise ctypes.WinError(ctypes.get_last_error()) # 示例用法 if __name__ == "__main__": monitors = get_monitor_devices() print("可用显示器设备名称:") for idx, dev in enumerate(monitors): print(f"{idx+1}. {dev}") # 为第一台显示器设置壁纸(可自行修改目标显示器) target_monitor = monitors[0] wallpaper_path = "wallpaper3.jpg" try: set_monitor_wallpaper(target_monitor, wallpaper_path) print(f"已成功为显示器 {target_monitor} 设置壁纸") except Exception as e: print(f"设置失败:{e}")
注意事项
- 系统版本限制:仅支持Windows 10 1607(周年更新)及以上版本,旧系统无
SetWallpaperForMonitor函数。 - 路径要求:必须传入壁纸文件的绝对路径,Python字符串默认是Unicode格式,符合API要求。
- 设备名称:运行代码后会打印所有显示器的设备名称(如
\\\\.\\DISPLAY1),可根据需求选择目标显示器。
内容的提问来源于stack exchange,提问作者pyjamas
相关产品推荐
相关产品推荐

