Windows 10设置桌面背景代码
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QWidget, QMessageBox, QStyleFactory
from PyQt5.QtGui import QIcon
import sys
import ctypes
import requests
import json
import time
from urllib.request import urlretrieve
import os
from PIL import Image
import win32api,win32con,win32gui
import re
import platform
import configparser
class Ui_Form(QWidget):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(450, 120)
Form.setMinimumSize(QtCore.QSize(450, 120))
Form.setMaximumSize(QtCore.QSize(500, 150))
Form.setWindowIcon(QIcon('Logo.png'))
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(20, 4, 101, 51))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(12)
self.cur_path = os.path.abspath(os.path.dirname(__file__))
self.settingfilename = 'setting.ini'
self.label.setFont(font)
self.label.setObjectName("label")
self.label.setStyle(QStyleFactory.create('Fusion'))
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(130, 19, 211, 25))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit.setStyle(QStyleFactory.create('Fusion'))
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(350, 14, 91, 31))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(12)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.pushButton.setStyle(QStyleFactory.create('Fusion'))
self.pushButton.clicked.connect(self.openDir)
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(20, 70, 130, 30))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(12)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_2.setStyle(QStyleFactory.create('Fusion'))
self.pushButton_2.clicked.connect(self.save_img)
self.pushButton_3 = QtWidgets.QPushButton(Form)
self.pushButton_3.setGeometry(QtCore.QRect(160, 70, 130, 30))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(12)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_3.setStyle(QStyleFactory.create('Fusion'))
if "Windows-7" in platform.platform():
self.pushButton_3.clicked.connect(self.set_wallpaper)
elif "Windows-10" in platform.platform():
self.pushButton_3.clicked.connect(self.set_wall_img)
else:
self.pushButton_3.clicked.connect(self.set_wallpaper)
self.pushButton_4 = QtWidgets.QPushButton(Form)
self.pushButton_4.setGeometry(QtCore.QRect(300, 70, 130, 30))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(12)
self.pushButton_4.setFont(font)
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_4.setStyle(QStyleFactory.create('Fusion'))
self.pushButton_4.clicked.connect(self.set_wallpaper_other)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.loadSetting()
self.lineEdit.setText(self.cur_path)
self.img_name = "img_%s.jpg"%time.strftime("%Y%m%d", time.localtime())
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "获取微软必应每日美图"))
self.label.setText(_translate("Form", "图片保存路径:"))
self.pushButton.setText(_translate("Form", "选择路径"))
self.pushButton_2.setText(_translate("Form", "获取今日图片"))
self.pushButton_3.setText(_translate("Form", "设置今日墙纸"))
self.pushButton_4.setText(_translate("Form", "更换其它墙纸"))
# 提示
def Tips(self, message):
QMessageBox.about(self, "提示", message)
# 打开文件夹
def openDir(self):
# pass
cur_path = QFileDialog.getExistingDirectory(self, "选取文件夹", self.cur_path)
if os.path.exists(cur_path):
self.lineEdit.clear()
self.lineEdit.setText(cur_path)
self.updateSetting()
# print(self.lineEdit.text())
# print(self.lineEdit.text())
else:
# pass
self.lineEdit.clear()
self.lineEdit.setText(self.cur_path)
# self.Tips('文件夹不存在!')
# 导入setting
def loadSetting(self):
if os.path.isfile(self.settingfilename):
config = configparser.ConfigParser()
config.read(self.settingfilename)
self.cur_path = config.get('WallPaper', 'PATH')
# 更新setting
def updateSetting(self):
config = configparser.ConfigParser()
# config.read(self.settingfilename)
# print(self.lineEdit.text())
config['WallPaper'] = {'PATH':self.lineEdit.text()}
with open(self.settingfilename, 'w') as f:
config.write(f)
def get_bing_img_url(self, format='js',idx=0):
'''
获取bing每日壁纸url
'''
url = 'https://cn.bing.com/HPImageArchive.aspx?format={}&idx={}&n=1'.format(format,idx)
try:
resp = requests.get(url,timeout=5).text
data = json.loads(resp)
return 'https://cn.bing.com{}'.format(data['images'][0]['url'])
except:
self.Tips('网络连接失败!')
def save_img(self):
filepath = self.get_bing_img_url()
try:
urlretrieve(filepath, self.lineEdit.text()+"/"+ self.img_name)
self.Tips("图片下载成功!")
except Exception as E:
self.Tips("错误!+%s"%E)
def set_wall_img(self):
img_path = self.lineEdit.text()+"/"+self.img_name
if os.path.exists(img_path):
try:
ctypes.windll.user32.SystemParametersInfoW(20,0,img_path,0)
self.Tips("桌面背景设置成功!")
except Exception as E:
self.Tips("错误! + %s"%E)
else:
self.Tips("今日图片文件不存在!")
def set_wallpaper_from_bmp(self,bmp_path):
#img_path = self.lineEdit.text()+"\\"+self.img_name
#print(img_path)
if os.path.exists(bmp_path):
try:
#打开指定注册表路径
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
#最后的参数:2拉伸,0居中,6适应,10填充,0平铺
win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
#最后的参数:1表示平铺,拉伸居中等都是0
win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
#刷新桌面
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,bmp_path,win32con.SPIF_SENDWININICHANGE)
self.Tips("桌面背景设置成功!")
except Exception as E:
self.Tips("错误! + %s"%E)
else:
self.Tips("今日图片文件不存在!")
def set_wallpaper(self):
#把图片格式统一转换成bmp格式,并放在源图片的同一目录
img_path = self.lineEdit.text()+"\\"+self.img_name
if os.path.exists(img_path):
try:
img_dir = os.path.dirname(img_path)
bmpImage = Image.open(img_path)
new_bmp_path = os.path.join(img_dir,"img_%s.bmp"%time.strftime("%Y%m%d", time.localtime()))
bmpImage.save(new_bmp_path, "BMP")
self.set_wallpaper_from_bmp(new_bmp_path)
except Exception as E:
self.Tips(E)
else:
self.Tips("今日图片文件不存在!")
def set_wallpaper_other(self):
img_name, img_type = QFileDialog.getOpenFileName(self, "选择文件", self.lineEdit.text(), "图片文件(*.jpg;*.jpeg;*.png;*.bmp)")
# print(img_name, img_type)
if os.path.exists(img_name):
try:
if "Windows-7" in platform.platform():
img_dir = os.path.dirname(img_name)
bmpImage = Image.open(img_name)
new_bmp_path = os.path.join(img_dir,"img_%s.bmp"%time.strftime("%Y%m%d", time.localtime()))
bmpImage.save(new_bmp_path, "BMP")
self.set_wallpaper_from_bmp(new_bmp_path)
elif "Windows-10" in platform.platform():
ctypes.windll.user32.SystemParametersInfoW(20,0,img_name,0)
elif "Windows-11" in platform.platform():
ctypes.windll.user32.SystemParametersInfoW(20,0,img_name,0)
else:
img_dir = os.path.dirname(img_name)
bmpImage = Image.open(img_name)
new_bmp_path = os.path.join(img_dir,"img_%s.bmp"%time.strftime("%Y%m%d", time.localtime()))
bmpImage.save(new_bmp_path, "BMP")
self.set_wallpaper_from_bmp(new_bmp_path)
except Exception as E:
self.Tips(E)
else:
self.Tips("未选取图片!")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Form()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())