参考:
https://blog.csdn.net/icevmj/article/details/78890552
https://blog.csdn.net/whl826661099/article/details/79624326#commentBox
window7 64位 python3.7.4
图片链接 https://area.sinaapp.com/bingImg/ 为 Bing 每日一图的地址,解析可以获得图片文件的地址。之后使用 ctypes 工具进行壁纸设置。再将py程序打包成exe文件,方便其他人。
其中,每日一图的地址是从其他博客找到的;在设置壁纸时,发现我的环境不支持.jpg设置,只能将下载的图片手动转换为bmp格式(直接下载为bmp格式也不行)。
最终实现生成exe文件,每天执行时自动设置壁纸
首先,pip install pyinstaller
其次,检查是否安装成功(在python\Scripts路径)
最后,将程序放到python\Scripts路径下,直接执行打包命令 pyinstaller -F hello.py //python\Scripts\dist 文件夹下会生成exe文件
最后附程序:
"""
程序功能:抓取bing每日一图,设置为桌面壁纸
"""
import urllib.request
import requests
import os.path
import ctypes
from PIL import Image
import re
# 请求网页,跳转到最终 img 地址
def get_img_url(raw_img_url = "https://area.sinaapp.com/bingImg/"):
r = requests.get(raw_img_url)
img_url = r.url # 得到图片文件的网址
print('img_url:', img_url)
return img_url
def save_img(img_url,dirname):
#保存图片到磁盘文件夹dirname中
try:
if not os.path.exists(dirname):
print ('文件夹',dirname,'不存在,重新建立')
#os.mkdir(dirname)
os.makedirs(dirname)
#获得图片文件名,包括后缀,过滤路径中不能作为文件路径的特殊符号
basename=re.sub(r"[\/\\\?:\*\"\<\>\|]",'_',os.path.basename(img_url))
#拼接目录与文件名,得到图片路径
filepath = os.path.join(dirname, basename+'.jpg')
#下载图片,并保存到文件夹中
urllib.request.urlretrieve(img_url,filepath)
except IOError as e:
print ('文件操作失败',e)
except Exception as e:
print ('错误 :',e)
print("Save", filepath, "successfully!")
return filepath
# 设置图片绝对路径 filepath 所指向的图片为壁纸
def set_img_as_wallpaper(filepath):
SPI_SETDESKWALLPAPER = 0x14 #which command (20)
SPIF_UPDATEINIFILE = 0x2 #forces instant update
#文件只能是bmp格式,且必须是经过转换的,直接下载为bmp格式设置不成功
filepathBMP=filepath.replace(".jpg",".bmp")
img = Image.open(filepath)
img.save(filepathBMP,'BMP')
print(ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, True, filepathBMP, SPIF_UPDATEINIFILE))
#SystemParametersInfoW instead of SystemParametersInfoA (W instead of A)
def main():
dirname = "D:\\bingImg" # 图片要被保存在的位置
img_url = get_img_url()
filepath = save_img(img_url, dirname) # 图片文件的的路径
set_img_as_wallpaper(filepath)
main()