You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现Windows 10壁纸定时从API获取并更换?

实现方案:Python自动从URL获取并设置Windows 10壁纸

核心思路

完全可以实现!因为Windows系统API确实只认本地文件路径,所以我们的流程是:

  • 从指定API获取动漫壁纸的URL
  • 将图片下载到本地临时目录(避免占用过多磁盘空间)
  • 调用Windows系统API(通过ctypes)设置本地图片为壁纸
  • 定时重复上述流程(每隔5分钟)

所需依赖

先安装需要的第三方库:

pip install requests schedule

完整代码实现

import requests
import ctypes
import os
import tempfile
import schedule
import time

# Windows API 常量定义
SPI_SETDESKWALLPAPER = 20
SPIF_UPDATEINIFILE = 0x01
SPIF_SENDCHANGE = 0x02

def set_wallpaper(image_path):
    """调用Windows API设置桌面壁纸"""
    # 转换路径为Unicode格式(Windows API要求)
    image_path = os.path.abspath(image_path)
    ctypes.windll.user32.SystemParametersInfoW(
        SPI_SETDESKWALLPAPER,
        0,
        image_path,
        SPIF_UPDATEINIFILE | SPIF_SENDCHANGE
    )

def get_anime_wallpaper_url():
    """从API获取随机动漫壁纸URL,需要替换成你实际使用的API"""
    # 示例:这里用占位API,你可以替换成Wallhaven、Konachan等动漫壁纸API
    api_url = "https://api.example.com/anime-wallpapers/random"
    try:
        response = requests.get(api_url)
        response.raise_for_status()
        data = response.json()
        # 假设API返回的图片URL在data['image_url']字段,需根据实际API调整
        return data.get('image_url')
    except Exception as e:
        print(f"获取壁纸URL失败: {e}")
        return None

def download_image_to_temp(url):
    """将网络图片下载到临时文件,返回本地文件路径"""
    if not url:
        return None
    try:
        response = requests.get(url, stream=True)
        response.raise_for_status()
        # 创建临时文件,后缀设为jpg(可根据实际图片格式调整)
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp_file:
            for chunk in response.iter_content(chunk_size=8192):
                temp_file.write(chunk)
            return temp_file.name
    except Exception as e:
        print(f"下载图片失败: {e}")
        return None

def update_wallpaper():
    """完整的壁纸更新流程"""
    print("开始更新壁纸...")
    wallpaper_url = get_anime_wallpaper_url()
    temp_image_path = download_image_to_temp(wallpaper_url)
    if temp_image_path:
        set_wallpaper(temp_image_path)
        print("壁纸更新成功!")
        # 可选:设置完壁纸后删除临时文件(取消注释即可)
        # os.unlink(temp_image_path)
    else:
        print("壁纸更新失败")

if __name__ == "__main__":
    # 程序启动时立即更新一次壁纸
    update_wallpaper()
    # 设置每隔5分钟自动执行一次更新
    schedule.every(5).minutes.do(update_wallpaper)
    # 保持程序持续运行
    print("程序已启动,将每隔5分钟自动更新壁纸...")
    while True:
        schedule.run_pending()
        time.sleep(1)

关键注意事项

  1. API适配:你需要修改get_anime_wallpaper_url函数里的API地址和返回字段解析逻辑,不同动漫壁纸API的返回结构差异很大,要根据实际情况调整。
  2. 权限问题:如果设置壁纸失败,尝试以管理员身份运行Python脚本,部分Windows环境下修改系统设置需要更高权限。
  3. 图片格式:确保下载的图片是Windows支持的格式(JPG、PNG等),如果API返回其他格式,记得调整临时文件的后缀。
  4. 临时文件:代码中创建的临时文件默认不会自动删除,你可以取消注释os.unlink(temp_image_path)一行,在设置完壁纸后清理文件。

内容的提问来源于stack exchange,提问作者Neophyte_Palaash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:27:55