电脑桌面随机切换壁纸

这是一个使用Python编写的脚本,用于自动更换壁纸。它会遍历指定目录下的所有jpg和png图片文件,随机选取一张作为桌面壁纸,并提供了一个GUI界面来启动和停止壁纸切换功能。用户可以设置壁纸更换的延迟时间。此外,脚本还包含了错误处理和多线程支持。
摘要由CSDN通过智能技术生成
import win32gui,win32con,win32api
import random
import time
import os
import sys

def setWallpaper(imagepath):
    k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 0 居中正常大小,2 拉伸铺满全屏
    win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,imagepath, 1+2)
    
def findfiles(path):
    # 首先遍历当前目录所有文件及文件夹
    file_list = os.listdir(path)
    # 循环判断每个元素是否是文件夹还是文件,是文件夹的话,递归
    for file in file_list:
    	# 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
        cur_path = os.path.join(path, file)
        # 判断是否是文件夹
        if os.path.isdir(cur_path):
            findfiles(cur_path)
        else:
            if "png" in file:
                result.append(file)
            if "jpg" in file:
                result.append(file)
    return result
    
result=[]
result = findfiles(os.getcwd()+"/壁纸")
t=sys.argv[1]
while True:
    index = random.randint(0,len(result)-1)
    print("本次生成随机数为:"+str(index))
    path = os.getcwd()+"/壁纸/"+result[index]
    setWallpaper(path)
    time.sleep(int(t))

将下载放在 壁纸文件夹,然后执行脚本
在这里插入图片描述

python 脚本名称 1

需要传入参数 ,1 是延迟时间(秒)

在这里插入图片描述
在这里插入图片描述

2022-07-01 更新

在这里插入图片描述
代码如下:

#!-*- coding:utf-8 -*-!
import tkinter as tk
import tkinter.font as tkFont
from tkinter.filedialog import askdirectory
import os
import win32gui,win32con,win32api
import random
import time
import threading
import inspect
import ctypes 
import tkinter.messagebox as mb
class App:
    def __init__(self, root):
        #setting title
        root.title("壁纸自动切换工具")
        #setting window size
        width=600
        height=300
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)
 
        GLabel_315=tk.Label(root)
        ft = tkFont.Font(family='Times',size=22)
        GLabel_315["font"] = ft
        GLabel_315["fg"] = "#333333"
        GLabel_315["justify"] = "center"
        GLabel_315["text"] = "随机壁纸"
        GLabel_315.place(x=190,y=50,width=202,height=41)
 
        GButton_379=tk.Button(root)
        GButton_379["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times',size=18)
        GButton_379["font"] = ft
        GButton_379["fg"] = "#000000"
        GButton_379["justify"] = "center"
        GButton_379["text"] = "启动"
        GButton_379.place(x=130,y=220,width=185,height=39)
        GButton_379["command"] = self.GButton_379_command
 
        GButton_380=tk.Button(root)
        GButton_380["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times',size=18)
        GButton_380["font"] = ft
        GButton_380["fg"] = "#000000"
        GButton_380["justify"] = "center"
        GButton_380["text"] = "停止"
        GButton_380.place(x=320,y=220,width=185,height=39)
        GButton_380["command"] = self.GButton_380_command
 
    
        
        GLineEdit_171=tk.Entry(root)
        GLineEdit_171["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=16)
        GLineEdit_171["font"] = ft
        GLineEdit_171["fg"] = "#333333"
        GLineEdit_171["justify"] = "center"
        GLineEdit_171["text"] = ""
        GLineEdit_171.place(x=130,y=120,width=254,height=36)
        GLineEdit_171["textvariable"]=path
 
        GButton_611=tk.Button(root)
        GButton_611["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times',size=16)
        GButton_611["font"] = ft
        GButton_611["fg"] = "#000000"
        GButton_611["justify"] = "center"
        GButton_611["text"] = "选择目录"
        GButton_611.place(x=390,y=120,width=105,height=38)
        GButton_611["command"] = self.GButton_611_command
 
        GLabel_616=tk.Label(root)
        ft = tkFont.Font(family='Times',size=16)
        GLabel_616["font"] = ft
        GLabel_616["fg"] = "#333333"
        GLabel_616["justify"] = "center"
        GLabel_616["text"] = ""
        GLabel_616["textvariable"]=label_text
        GLabel_616.place(x=130,y=170,width=364,height=40)
         
    def _async_raise(self,tid, exctype):
        """raises the exception, performs cleanup if needed"""
        if not inspect.isclass(exctype):
            exctype = type(exctype)
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
        if res == 0:
            raise ValueError("invalid thread id")
        elif res != 1:
            # """if it returns a number greater than one, you're in trouble, 
            # and you should call it again with exc=NULL to revert the effect"""
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
            raise SystemError("PyThreadState_SetAsyncExc failed")
             
    def stop_thread(self, thread):
        self._async_raise(thread.ident, SystemExit)
         
    def thread(self):
        while True:
            index = random.randint(0,len(result)-1)
           # print("本次生成随机数为:"+str(index))
            wallpaper_path =path.get()+"/"+ result[index]
            k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
            win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 0 居中正常大小,2 拉伸铺满全屏
            win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
            win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,wallpaper_path, 1+2)
            time.sleep(1)
             
    def GButton_379_command(self):
        edit_text=path.get()
        if edit_text!="" and edit_text!=None:
            threads = threading.enumerate()
            for thread in threads:
                if thread ==threading.main_thread():
                    pass
                else:
                    self.stop_thread(thread)
            t1=threading.Thread(target=self.thread)
            t1.start()
            mb.showinfo('提示', '壁纸切换已启动')
             
    def GButton_380_command(self):
        edit_text=path.get()
        if edit_text!="" and edit_text!=None:
            threads = threading.enumerate()
            for thread in threads:
                if thread ==threading.main_thread():
                    pass
                else:
                    self.stop_thread(thread)
            mb.showinfo('提示', '壁纸切换已停止')
    def findfiles(self,path):
        file_list = os.listdir(path)
        # 循环判断每个元素是否是文件夹还是文件,是文件夹的话,递归
        for file in file_list:
        # 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目              
            cur_path = os.path.join(path, file)
            # 判断是否是文件夹
            if os.path.isdir(cur_path):
                self.findfiles(cur_path)
            else:
                if "jpg" in file:
                    # 判断是否是特定文件名称
                    result.append(file)
                elif "png" in file:
                    # 判断是否是特定文件名称
                    result.append(file)
                elif "jpeg" in file:
                 # 判断是否是特定文件名称
                    result.append(file)
                else:
                    pass
        return result  
    def GButton_611_command(self):
        path_= askdirectory(parent=root, title="选择壁纸目录") #使用askdirectory()方法返回文件夹的路径
        path.set(path_)
        edit_text=path.get()
        global result
        result=[]
        if edit_text!="" and edit_text!=None:
            result=self.findfiles(edit_text)
            label_text.set("共找到"+str(len(result))+"张图片")
        else:
            label_text.set("")
if __name__ == "__main__":
    root = tk.Tk()
    path =tk.StringVar()
    label_text =tk.StringVar()
    app = App(root)
    root.mainloop()

软件打包命令

pyinstaller -F -w -i  ico图标  py文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
程序支持三种更换桌面换壁纸方式:开机自动更换,定时更换,热键更换(热键可以设置) 只要您指定壁纸文件所在文件夹,程序将该文件夹下(含所有子文件夹)所有的JPEG、GIF、TIF、PNG、JPE、JPG、BMP文件自动随机设置为桌面壁纸,使您的桌面壁纸随时都在变化。如果文件夹下的文件发生变化,程序会自动监控到并进行更新。 1、开机自动更换壁纸,前提当然得要将该程序设置为开机自动运行(本程序自动最小化加入到系统托盘)。 2、定时更换壁纸,只要您设置了时间间隔并启用定时更换功能,即可定时更换。 3、手动更换,在任何界面下按热键键即可马上更换壁纸(默认热键为CTRL+ALT+P,可以在设置中更改)。 本程序系VB2008编写,可在windows XP 及Vista下运行(在XP下需要安装.NET Framework2.0组件,请从微软官方网站下载。 安装方法: 方法一:解压缩后,运行“自动更换壁程序.application”即可安装程序,安装完后会在开始菜单建立菜单。 方法二:解压缩后,可以不进行安装,直接运行“Application Files\自动更换壁程序_1_0_0_2\自动更换壁程序.exe”即可,此时不会在开始菜单建立程序组。 首次运行本程序时,会自动弹出设置窗口,要求您指定壁纸文件所在文件夹等选项。如果您要将程序设置为开机自动运行,请选中“设置为开机自动运行并更换壁纸”复选框,取消该复选框则可以取消开机自动运行。 如果您对本程序有何建议或意见,请与本人联系 姓名:游平 地址:湖南省 株洲市 215信箱 财务处 邮编:412002 邮箱:myyouping@hotmail.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈增林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值