關鍵詞:讀取檔案夾、讀取檔案、作業系統、設定壁紙、移動檔案
預期實作如下幾個步驟
1、獲取指定檔案夾內所有圖片名
2、隨機取一張圖片設定為壁紙
3、設定為壁紙的圖片移動到另外一個檔案夾中
第一步,獲取指定檔案夾內所有圖片名
C盤background有兩個檔案夾,now檔案夾存放是預備設定為壁紙的圖片,ok檔案夾存放已經設定為壁紙的圖片

獲取檔案夾內所有圖片需要匯入os庫,代碼如下
# -*- coding: utf-8 -*- import os filePath = 'C:\\background\\' test = os.listdir(filePath+"now\\")
列印test數列

第二部,隨機取值,從獲取的圖片名稱串列中隨機取出一個值,設定為壁紙,需要匯入random庫,代碼如下
image_path = random.choice(test) setWallpaper(filePath+"now\\"+image_path)
定義的設定為壁紙的方法,上方代碼中的setWallpaper
def setWallpaper(image_path): key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2") win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,image_path, 1+2)
第三步,將設定好的圖片移動到其他檔案夾內,需要匯入shutil庫
shutil.move(filePath+"now\\"+image_path, filePath+"ok\\")
如此,實作了開頭的1/2/3步驟,串起來整個腳本如下,可放在桌面上,壁紙看膩了,點一下就切換了,換個思路,可以從網上直接取圖設定壁紙也是可行的
# -*- coding: utf-8 -*- import win32api import win32con import win32gui import os import random import shutil #設定圖片為桌面背景,參考地址https://blog.csdn.net/zwvista/article/details/18655 def setWallpaper(image_path): key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2") win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,image_path, 1+2) #獲取指定目錄下所有檔案名稱,參考地址https://blog.csdn.net/zhuzuwei/article/details/79925562 filePath = 'C:\\background\\' test = os.listdir(filePath+"now\\") #從獲取的圖片名稱串列中隨機取出一個值,設定為壁紙,隨機取值參考https://blog.csdn.net/weixin_39791387/article/details/84958436?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase image_path = random.choice(test) setWallpaper(filePath+"now\\"+image_path) #將設定好的圖片移動到其他檔案夾內,參考https://blog.csdn.net/silentwolfyh/article/details/74931123 shutil.move(filePath+"now\\"+image_path, filePath+"ok\\") print("設定成功")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/265037.html
標籤:Python
