python - 在 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
解决方案
对于 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 也更好地突出了这一点。
推荐阅读
- mysql - 对于我写的以下查询,我收到“标量子查询包含多行”。有人可以纠正我吗?
- sql - 显示来自用户输入的 sql 数据
- c# - Xamarin Android - 尽管一切都已实现,但地理围栏服务无法正常工作
- constraint-programming - 如何在灵活的工作车间中编写操作的后续操作在同一台机器上完成的代码?
- postgresql - Postgres 在通过 JBOSS 运行我的应用程序时出现致命错误
- node.js - 在同一个 ubuntu 服务器上使用相同的 Nginx 为两个网站提供服务重定向到同一个网站
- python-3.x - 在时间序列中找到阶梯(或尖峰)形状的pythonic方法是什么?
- c++ - 如何解码 USB 设备标签
- powershell - 从列分隔的文本文件中删除 ID/护照号所需的 Powershell 命令
- oracle-apex-5.1 - Oracle APEX - 有没有办法从列表条目中调用 javaScript