代码主要参考懒人壁纸工具,完全不占内存。会功成身退的壁纸工具(出处: 吾爱破解论坛)如下图。
写这个的原因同上图(就是在原博主的代码上进行了一些修改)。
原代码
import os
import requests
import ctypes
import json
import configparser
import shutil
from datetime import date
def download_image(url, save_path):
try:
response = requests.get(url)
response.raise_for_status()
with open(save_path, 'wb') as file:
file.write(response.content)
print("图片下载成功!")
except requests.HTTPError as e:
print(f"图片下载失败:{e}")
def set_wallpaper(image_path):
# 设置桌面背景
SPI_SETDESKWALLPAPER = 0x0014
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, image_path, 3)
print("桌面背景设置成功!")
# 读取配置文件
config = configparser.ConfigParser()
config.read('set.ini')
path = config.get('Settings', 'path')
boot = config.get('Settings', 'boot')
# 解析链接获取图片地址
url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"
response = requests.get(url)
data = response.json()
image_url = "https://cn.bing.com" + data['images'][0]['url']
# 图片保存目录
save_dir = path
# 获取今天的日期,并构建图片保存文件名
today = date.today()
save_file_name = today.strftime("%Y%m%d") + ".jpg"
# 图片保存路径和文件名
save_file_path = os.path.join(save_dir, save_file_name)
# 检查保存目录是否存在,如果不存在则新建目录
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 下载图片
download_image(image_url, save_file_path)
# 设置桌面背景
set_wallpaper(save_file_path)
# 判断是否添加到计算机启动项
current_path = os.getcwd()
shortcut_path = os.path.join(os.environ["APPDATA"], "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "WallpaperChanger.lnk")
if boot.lower() == "yes": # 添加到计算机启动项
shutil.copyfile(os.path.join(current_path, "WallpaperChanger.lnk"), shortcut_path)
print("已添加到计算机启动项")
elif boot.lower() == "no": # 从计算机启动项移除
if os.path.exists(shortcut_path):
os.remove(shortcut_path)
print("已从计算机启动项移除")
else:
print("boot值非法,无法处理")
# 关闭程序
exit()
修改代码
import os
import requests
import ctypes
import configparser
from datetime import date, datetime, timedelta
import sys
import win32com.client
def log(string: str):
print(datetime.now().strftime("[%Y-%m-%d %H:%M:%S.%f]") + '\t' + string)
def download_image(image_url, save_path):
try:
response = requests.get(image_url)
response.raise_for_status()
with open(save_path, 'wb') as file:
file.write(response.content)
log("图片下载成功!")
except requests.HTTPError as e:
log(f"图片下载失败:{e}")
def set_wallpaper(image_path):
# 设置桌面背景
spi_set_desk_wallpaper = 0x0014
ctypes.windll.user32.SystemParametersInfoW(spi_set_desk_wallpaper, 0, image_path, 3)
log("桌面背景设置成功!")
def main():
# 读取配置文件
config = configparser.ConfigParser()
config.read('set.ini')
path = config.get('Settings', 'path')
boot = config.get('Settings', 'boot')
log_path = config.get('Settings', 'log_path')
log_restore = config.getint('Settings', 'log_restore')
# 日志处理
if not os.path.exists(log_path):
os.makedirs(log_path)
else:
if log_restore <= 0:
log_restore = 3
past_time = datetime.now() - timedelta(days=log_restore)
for file_name in os.listdir(log_path):
# 日志文件名符合log_%Y%m%d.txt
# 解析文件名中的日期部分
date_str = file_name.split("_")[1].split(".")[0]
file_date = datetime.strptime(date_str, "%Y%m%d")
# 删除过期文件
if file_date < past_time:
os.remove(os.path.join(log_path, file_name))
with open(os.path.join(log_path, 'log_' + date.today().strftime("%Y%m%d") + '.txt'), 'a',
encoding='utf-8') as log_file:
sys.stdout = log_file
sys.stderr = log_file
log('----------------Start----------------')
# 图片保存目录
save_dir = path
# 检查保存目录是否存在,如果不存在则新建目录
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 获取今天的日期,并构建图片保存文件名
save_file_name = date.today().strftime("%Y%m%d") + ".jpg"
# 图片保存路径和文件名
save_file_path = os.path.join(save_dir, save_file_name)
if not os.path.exists(save_file_path):
# 解析链接获取图片地址
url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"
response = requests.get(url)
data = response.json()
image_url = "https://cn.bing.com" + data['images'][0]['url']
# 下载图片
download_image(image_url, save_file_path)
else:
log('文件已存在')
# 设置桌面背景
set_wallpaper(save_file_path)
# 判断是否添加到计算机启动项
shortcut_path = os.path.join(os.environ["APPDATA"], "Microsoft", "Windows", "Start Menu", "Programs", "Startup",
"WallpaperChanger.lnk")
if boot.lower() == "yes": # 添加到计算机启动项
if not os.path.exists(shortcut_path):
# 创建快捷方式到启动项
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortcut(shortcut_path)
shortcut.TargetPath = os.path.join(os.getcwd(), 'WallpaperChanger.exe')
shortcut.WorkingDirectory = os.getcwd()
shortcut.Save()
log("添加到计算机启动项")
else:
log("启动项已存在")
elif boot.lower() == "no": # 从计算机启动项移除
if os.path.exists(shortcut_path):
os.remove(shortcut_path)
log("已从计算机启动项移除")
else:
log("启动项不存在,无需删除")
else:
log("boot值非法,无法处理")
log('-----------------End-----------------\n')
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
# 关闭程序
sys.exit()
if __name__ == '__main__':
main()
编译及使用
使用python3.9版本(3.8也行,不要用3.11版本,conda下载的pyinstaller不知道有什么问题,打包成的exe一运行就报错。其他版本没测试过)
使用 pyinstaller -F -w -n WallpaperChanger main.py
编译打包,生成执行文件WallpaperChanger .exe
在运行时,需要在WallpaperChanger .exe
同级目录下新建配置文件set.ini
其中配置示例如下:
[Settings]
path = D:\Pictures
boot = yes
log_path = .\log
log_restore = 7
其中
path
为图像保存的位置boot
表示是否添加到启动项,yes
为添加到启动项no
为从启动项删除,大小写不限log_path
为日志文件的位置log_restore
为日志保存时间,单位为天,若填写小于等于0的数,默认为3
改动
- 原代码每次启动都会做出所有操作,下载图片、设置壁纸、添加启动项。修改后不然,只有当日图片未下载才会下载,只有启动项中没有才会添加启动项。
- 原代码会显示控制台,并将一些信息打印出来,这其实很丑。编译时使用
-w
参数即可。 - 使用日志文件,将运行信息打印到日志文件中。
- 自定义日志文件保存天数(其实就是,每次运行会把不需要继续保存的文件删掉)。
- 原代码需要自己新建快捷方式,并将名字改为
"WallpaperChanger.lnk"
,现在这一步完全自动化。