前言
最近用腾讯桌面整理的时候总感觉壁纸不舒服,于是便想着自己做一个,非常简陋的一个小工具,还有几个功能待完善,随缘更新吧。
随机图片源:https://api.btstu.cn/doc/sjbz.php
使用效果
源码
有两个GUI版本
wxpython:
# -*- coding:utf-8 -*-
import sys
import wx,win32api,win32gui,win32con,requests,json,os,wx.adv
def setWallPaper(pic):
regkey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(regkey, "WallpaperStyle", 0, win32con.REG_SZ, "2")
win32api.RegSetValueEx(regkey, "TileWallpaper", 0, win32con.REG_SZ, "0")
# refresh screen
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, pic, win32con.SPIF_SENDWININICHANGE)
def setAutoRun(prog_path):
regkey = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, win32con.KEY_SET_VALUE)
win32api.RegCreateKey(regkey,"setWallPaper",0,win32con.REG_SZ,prog_path)
def getImage(typeChooses):
result = requests.get("https://api.btstu.cn/sjbz/api.php?lx="+typeChooses+"&format=json")
img = requests.get(json.loads(result.text)["imgurl"]).content
imgname = json.loads(result.text)["imgurl"].split("/")[4]
imgpath = downloadImage(img,imgname,typeChooses)
return imgpath
def downloadImage(img,imgname,typeChooses):
workpath = os.getcwd()
if workpath.partition("\\")[2] == "":
savepath = workpath+"images\\"+typeChooses
else:
savepath = workpath + "\\images\\" + typeChooses
imgpath = savepath + "\\" + imgname
if not os.path.exists(workpath+"\\images\\"):
os.mkdir(workpath + "\\images\\")
if not os.path.exists(savepath) :
os.mkdir(savepath)
with open(imgpath ,"wb+") as file:
file.write(img)
file.close()
return imgpath
class MainFrame(wx.Frame):
def __init__(self):
self.frame = wx.Frame.__init__(self,None,title="随机壁纸切换工具",size=(300,120),name="随机壁纸切换工具")
self.qdck = wx.Panel(self)
self.Centre()
self.SetIcon(wx.Icon("I:\\personal-code\\temp\\icon.png",wx.BITMAP_TYPE_PNG))
self.hbox1 = wx.BoxSizer(wx.HORIZONTAL)
self.an1 = wx.Button(self.qdck, size=(60, 40), pos=(10, 30), label='切换图片', name='button')
self.an1.SetForegroundColour((54, 57, 60, 255))
self.an1.SetOwnBackgroundColour((238, 238, 238, 255))
self.an1.Bind(wx.EVT_BUTTON, self.changeImage)
self.box_one = wx.BoxSizer(wx.HORIZONTAL)
self.text = wx.StaticText(self.qdck,label='选择图片类型:',size=(40,20),pos=(0,0))
self.list = ["妹子图","二次元","风景","纯随机"]
self.select = wx.ComboBox(self.qdck,-1,value="妹子图",choices=self.list,style=wx.CB_SORT,size=(40,100),pos=(0,0))
self.box_one.Add(self.text,1,flag=wx.LEFT|wx.RIGHT|wx.FIXED_MINSIZE,border=10)
self.box_one.Add(self.select,1,flag = wx.ALL|wx.FIXED_MINSIZE)
self.bbox = wx.BoxSizer(wx.VERTICAL)
self.bbox.Add(self.box_one,1,flag = wx.ALL|wx.EXPAND,border = 7)
self.qdck.SetSizer(self.bbox)
self.Bind(wx.EVT_COMBOBOX,self.typeChoose,self.select)
self.Bind(wx.EVT_CLOSE,self.OnClose)
self.Bind(wx.EVT_ACTIVATE,self.setAutoRun)
self.typeChooses = "妹子图"
self.taskbar = taskbar(self)
def setAutoRun(self,event):
prog_path = os.path.realpath(__file__)
print(prog_path)
# setAutoRun()
def OnClose(self,event):
self.re = wx.MessageBox("是否最小化运行?",caption="Message",style=wx.OK|wx.CANCEL|wx.ICON_QUESTION)
if self.re == wx.OK:
self.Hide()
else:
taskbar(self).Destroy()
wx.Exit()
def typeChoose(self,event):
self.typeChooses = event.GetString()
def changeImage(self,event):
if self.typeChooses == "妹子图":
imgpath = getImage("meizi")
elif self.typeChooses == "二次元":
imgpath = getImage("dongman")
elif self.typeChooses == "风景":
imgpath = getImage("fengjing")
else:
imgpath = getImage("suiji")
setWallPaper(imgpath)
class MainApp(wx.App):
def OnInit(self):
self.iMainFrame = MainFrame()
self.iMainFrame.Show(True)
return True
class taskbar(wx.adv.TaskBarIcon):
icon = "I:\\personal-code\\temp\\icon.png"
def __init__(self,frame):
wx.adv.TaskBarIcon.__init__(self)
self.SetIcon(wx.Icon(self.icon))
self.frame = frame
def setMenuItemData(self):
return (("打开主界面", self.OnOpenFrame), ("切换图片", self.OnSwitch), ("关闭", self.OnClose))
# 创建菜单
def CreatePopupMenu(self):
menu = wx.Menu()
for itemName, itemHandler in self.setMenuItemData():
if not itemName: # itemName为空就添加分隔符
menu.AppendSeparator()
continue
menuItem = wx.MenuItem(None, wx.ID_ANY, text=itemName, kind=wx.ITEM_NORMAL) # 创建菜单项
menu.Append(menuItem) # 将菜单项添加到菜单
self.Bind(wx.EVT_MENU, itemHandler, menuItem)
return menu
def OnOpenFrame(self, event):
self.frame.Show()
def OnSwitch(self, event):
self.frame.changeImage(event)
def OnClose(self, event):
self.Destroy()
wx.Exit()
if __name__ == '__main__':
app = MainApp()
app.MainLoop()
Pyqt5
# -*- coding: utf-8 -*-
import sys,win32api,win32gui,win32con,requests,json,os
import time
from PyQt5 import QtCore, QtGui, QtWidgets
def setWallPaper(pic):
regkey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(regkey, "WallpaperStyle", 0, win32con.REG_SZ, "2")
win32api.RegSetValueEx(regkey, "TileWallpaper", 0, win32con.REG_SZ, "0")
# refresh screen
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, pic, win32con.SPIF_SENDWININICHANGE)
def setAutoRun(prog_path):
regkey = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, win32con.KEY_SET_VALUE)
win32api.RegCreateKey(regkey,"setWallPaper",0,win32con.REG_SZ,prog_path)
def getImage(typeChooses):
result = requests.get("https://api.btstu.cn/sjbz/api.php?lx="+typeChooses+"&format=json")
img = requests.get(json.loads(result.text)["imgurl"]).content
imgname = json.loads(result.text)["imgurl"].split("/")[4]
imgpath = downloadImage(img,imgname,typeChooses)
return imgpath
def downloadImage(img,imgname,typeChooses):
workpath = os.getcwd()
if workpath.partition("\\")[2] == "":
savepath = workpath+"images\\"+typeChooses
else:
savepath = workpath + "\\images\\" + typeChooses
imgpath = savepath + "\\" + imgname
if not os.path.exists(workpath+"\\images\\"):
os.mkdir(workpath + "\\images\\")
if not os.path.exists(savepath) :
os.mkdir(savepath)
with open(imgpath ,"wb+") as file:
file.write(img)
file.close()
return imgpath
class timeRun(QtCore.QThread):
def __init__(self,time=None,parent=None):
super(timeRun, self).__init__()
self.time = time
self.parent = parent
def __del__(self):
self.wait()
def run(self):
while True:
time.sleep(self.time)
MainWindow.switch_wall(self.parent)
def loadConfig():
test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
test_dict = json.dumps(test_dict)
with open("./config.json","w") as file:
json.dump(test_dict,file)
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setupUi()
self.tray = TrayIcon(self)
self.tray.show()
def setupUi(self):
self.setMaximumSize(280, 70)
self.setMinimumSize(280, 70)
self.centralwidget = QtWidgets.QWidget(self) # 设置UI
self.GridLayout = QtWidgets.QGridLayout(self.centralwidget) # 设置自动放大缩小
self.setWindowTitle("随机壁纸切换工具")
self.icon = QtGui.QIcon()
self.icon.addPixmap(QtGui.QPixmap("I:\\personal-code\\temp\\icon.ico"),QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.setWindowIcon(self.icon)
self.type_label = QtWidgets.QLabel(self.centralwidget)
self.type_label.setText("选择壁纸类型:")
self.GridLayout.addWidget(self.type_label,0,0,1,1)
self.type_combo = QtWidgets.QComboBox(self.centralwidget)
self.type_combo.addItem("妹子图")
self.type_combo.addItem("动漫")
self.type_combo.addItem("风景")
self.type_combo.addItem("随机")
self.GridLayout.addWidget(self.type_combo,0,2,1,1)
self.time_label = QtWidgets.QLabel(self.centralwidget)
self.time_label.setText("自动切换:")
self.GridLayout.addWidget(self.time_label,1,0,1,1)
self.time_combo = QtWidgets.QComboBox(self.centralwidget)
self.time_combo.addItem("不自动切换")
self.time_combo.addItem("10分钟")
self.time_combo.addItem("20分钟")
self.time_combo.addItem("30分钟")
self.time_combo.addItem("1小时")
self.GridLayout.addWidget(self.time_combo,1,2,1,1)
self.boot_auto = QtWidgets.QCheckBox(self.centralwidget)
self.boot_auto.setText("开机自启")
self.GridLayout.addWidget(self.boot_auto,0,3,1,1)
self.switch_btn = QtWidgets.QPushButton(self.centralwidget)
self.switch_btn.setText("切换壁纸")
self.GridLayout.addWidget(self.switch_btn,1,3,1,1)
self.switch_btn.clicked.connect(self.switch_wall)
self.boot_auto.stateChanged.connect(self.boot)
self.time_combo.activated.connect(self.time_combos)
# self.setCentralWidget(self.centralwidget) # 主界面使用UI格式
loadConfig()
print(self.isActiveWindow())
self.show()
print(self.isActiveWindow())
def time_combos(self):
if self.time_combo.currentText() == "10分钟":
self.timestate = 5
elif self.time_combo.currentText() == "20分钟":
self.timestate = 20
elif self.time_combo.currentText() == "30分钟":
self.timestate = 30
elif self.time_combo.currentText() == "1小时":
self.timestate = 40
else:
self.timestate = 0
self.time_run = timeRun(self.timestate, self)
if self.timestate != 0:
self.time_run.start()
elif self.time_run.isRunning():
self.time_run.quit()
def boot(self):
print(os.path.realpath(__file__))
def closeEvent(self,event):
reply = QtWidgets.QMessageBox.information(self.centralwidget, '提示', "是否最小化运行?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes)
# 判断返回值,如果点击的是Yes按钮,我们就关闭组件和应用,否则就忽略关闭事件
if reply == 16384:
print(True)
self.hide()
event.ignore()
else:
event.accept()
def switch_wall(self):
if self.type_combo.currentText() == "妹子图":
imgpath = getImage("meizi")
elif self.type_combo.currentText() == "二次元":
imgpath = getImage("dongman")
elif self.type_combo.currentText() == "风景":
imgpath = getImage("fengjing")
else:
imgpath = getImage("suiji")
setWallPaper(imgpath)
class TrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self,parent=None):
super(TrayIcon,self).__init__(parent)
self.showMenu()
self.events()
def showMenu(self):
self.menu = QtWidgets.QMenu()
self.showAction2 = QtWidgets.QAction("切换壁纸", self, triggered=self.switch_wall)
self.quitAction = QtWidgets.QAction("退出", self, triggered=self.close_prog)
self.menu.addAction(self.showAction2)
self.menu.addAction(self.quitAction)
self.setContextMenu(self.menu)
def events(self):
self.activated.connect(self.iconClied)
# 把鼠标点击图标的信号和槽连接
self.setIcon(QtGui.QIcon("I:\\personal-code\\temp\\icon.ico"))
self.icon = self.MessageIcon()
# 设置图标
def iconClied(self, reason):
"鼠标点击icon传递的信号会带有一个整形的值,1是表示单击右键,2是双击,3是单击左键,4是用鼠标中键点击"
if reason == 3:
try:
if self.parent().show():
pass
else:
self.parent().show()
except BaseException as e:
self.showMessage("提示",str(e), self.icon)
def switch_wall(self):
MainWindow.switch_wall(self.parent())
def close_prog(self):
"保险起见,为了完整的退出"
self.setVisible(False)
self.parent().exit()
sys.exit()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
mainwindow = MainWindow()
sys.exit(app.exec_())
Comments NOTHING