先说明下环境先,win10,python3.5-32位,编码软件vscode
由于经常喜欢换背景图片,所以干脆直接想着做了个改变背景的小程序算了,然后网上找了找就有这么一篇
https://blog.csdn.net/qinyuanpei/article/details/79279831
感谢这篇博主,刚开始还不知道可以添加注册表就能右键运行程序的,在这里学到了
好了贴上我的代码
import win32api
import win32gui
import win32con
import os
import sys
import re
import logging
def get_all_imgName(img_dir):
"""
扫描目录
:param img_dir 图片目录
:return imgages 图片列表
"""
imgDir = img_dir
images = []
if not os.path.exists(imgDir):
logging.error('Image store does not exist.')
return False
for root,dirs,files in os.walk(imgDir):# 获取imgDir下的root表示路径,dirs表示所有文件夹,files表示所有文件
images = files
return images
def get_imgName(img_dir,record_file):
"""
获取图片名字
:param img_dir 图片目录
:param record_file 记录文件
随机获取会浪费时间,既然都不能指定就直接取第一个
"""
logging.info('Get image name.')
imgDir = img_dir
recordFile = record_file
imgNamelist = get_all_imgName(imgDir)
if imgNamelist == False:
logging.error('Cannot get image name.')
return False
if len(imgNamelist) == 0:
logging.error('Image store empty.')
return False
return checkout_imgName(imgNamelist[0],imgDir,recordFile)
def record_imgName(img_name,record_file):
"""
记录图片文件名
:param img_name 图片名
:param record_file 记录文件
数据保存在record.csv文件中
这个文件将在执行文件的当前目录创建
"""
imageName = img_name
recordFile = record_file
imageName = imageName+'\n'
if not os.path.exists(recordFile):
logging.error('record.csv does not exist.')
return False
with open(recordFile,'a+') as fp:
fp.write(imageName)
return True
def deleteImage(img_path):
"""
删除图片
:param img_path 图片路径
"""
imgPath = img_path
if not os.path.exists(imgPath):
logging.info('Deleted image does not exist.')
return
os.remove(imgPath)
def checkout_imgName(new_Image_Name,img_dir,record_file):
"""
选择的图片是否曾经记录过
:param new_Image_Name 新图片名字
:param img_dir 图片目录
:param record_file 记录文件
这里只比较名字,因为在同一个地方下载都不可能出现同一个名字
"""
imageName = new_Image_Name
imgDir = img_dir
recordFile = record_file
recordList = read_used_imgName(recordFile)
if imageName in recordList: # 图片已经用过了
deleteImage(imgDir+imageName) # 删除图片
imageName = get_imgName(imgDir,record_file) # 获取新的图片
return checkout_imgName(imageName,imgDir,recordFile)
return imageName
def read_used_imgName(record_file):
"""
读取记录
:param record_file 记录文件
"""
recordFile = record_file
imageNames = []
if not os.path.exists(recordFile):
logging.error('record.csv does not exist.')
try:
with open(recordFile,'r') as fp:
lines = fp.readlines()
for line in lines:
imageNames.append(line.strip('\n'))
except:
logging.warning('record.csv read faild.')
return imageNames
def change_bg(dir_Path,img_name):
"""
更换壁纸
:param dir_Path 图片目录路径
:param img_name 图片名
"""
logging.info('Change desktop wallpaper')
path = dir_Path+img_name
key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0")
#2拉伸适应桌面,0桌面居中
win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, 1+2)
def main(image_dir,record_file):
imgName = get_imgName(image_dir,record_file)
change_bg(image_dir,imgName)
record_imgName(imgName,record_file)
if __name__ == '__main__':
exePath = sys.argv[0] # 工作路径
if exePath.find('/') != -1: # py执行
exeName = re.findall(r'[A-Za-z0-9]*.py$',exePath)[0]
work_dir = exePath[0:len(exePath)-len(exeName)]
image_dir = work_dir + 'images/'
record_file = work_dir + 'record.csv'
log = work_dir + 'run.log'
elif exePath.find('\\') != -1: # exe执行
exeName = re.findall(r'[A-Za-z0-9]*.exe$',exePath)[0]
work_dir = exePath[0:len(exePath)-len(exeName)]
image_dir = work_dir + 'images\\'
record_file = work_dir + 'record.csv'
log = work_dir + 'run.log'
logging.basicConfig(filename=log,format="[%(asctime)s-%(name)s-%(levelname)s]: %(message)s",level=logging.DEBUG) # 初始化日志路径,以及等级
logging.info('Program initialization.')
main(image_dir,record_file)
现在做出来的功能就这在一个py文件里,本来还想加个爬虫功能,但是使用scrapy等都不好爬取百度壁纸,暂时还没有写出来,但是使用selenium爬取百度图片已经写出来的,那边博客也已经写出来了,需要的可以去看看,因为selenium需要用到浏览器驱动什么的,不好集成到这个程序里面去。
py文件打包成exe很简单,pip下载pyinstaller,关于pyinstaller使用网上一找就有了,然后就可以直接打包成exe。在打包成exe后还要再exe同级目录下创建images文件夹和record.csv文件,一个是图片储存,一个是记录使用过的图片文件名的,记得使用的时候需要往images文件夹放入图片,日志方面还是很简单的,刚学了logging模块,日志文件会自动创建。
最后关于注册表的用法
首先在 运行-》输入regedit-》打开注册表-》找到 计算机\HKEY_CLASSES_ROOT\Directory\Background\shell\
在shell下面创建一个 项 为wallpaper ,再在wallpaper下面创建一个 项 为command,然后右击右边的默认两字
在 数据数值 那里填下你的exe文件的绝对路径
最后你在桌面右键就可以看到有 wallpaper 了。
好了,若有什么问题或者有兴趣交流python,java的朋友加我QQ:1193984561