今天我們繼續用Python寫一個小工具,一方面實現壁紙自由,另一方面實現桌面更換自由!
我們這里使用一個開源在 GitHub 上的必應壁紙 API 作為壁紙的來源
https://github.com/zenghongtu/bing-wallpaper
圖片
從 readme 當中我們可以知道,在 web 應用中我只需要使用如下引用即可
<img src="https://bingw.jasonzeng.dev/?w=800"/>
實在是太方便了
下面我們來看下該 API 的具體調用規則
UHD1920x12001920x10801366x7681280x7681024x768800x600800x480768x1280720x1280640x480480x800400x240320x240240x320
UHD 就是高清,圖片比較大。
我們直接在瀏覽器輸入如下地址
http://bingw.jasonzeng.dev?resolutinotallow=UHD&index=random&w=1000&format=json
Output:
{ "startdate": "20220105", "copyright": "Plate-billed mountain toucan in Bellavista Cloud Forest Reserve, Ecuador (? Tui De Roy/Minden Pictures)", "urlbase": "/th?id=OHR.MountainToucan_EN-US7120632569", "title": "A plate-billed mountain toucan", "url": "https://www.bing.com/th?id=OHR.MountainToucan_EN-US7120632569_UHD.jpg&w=1000"}
可以說是相當方便了
也可以直接在 css 當中使用
background-image: url(https://bingw.jasonzeng.dev/?index=random);height: 100%;background-position: center;background-repeat: no-repeat;background-size: cover;
下面我們看一下如何通過 Python 進行調用,也很簡單
import requestsdef get_wallpaper(): for i in range(30): url = "https://bingw.jasonzeng.dev?resolutinotallow=UHD&index=%s" % str(i) print(url) res = requests.get(url) with open("wallpaper/" + "%s.jpg" % str(i),"wb") as w: w.write(res.content)if __name__ == "__main__": get_wallpaper()
上面代碼就是獲取前30張壁紙,我們可以修改range的參數,來獲取不同數量的壁紙
抓取效果如下
圖片
壁紙有了,下面我們就來進行自動切換桌面壁紙,這里使用win32con和win32gui操作桌面壁紙
def windows_img(paper_path): k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control panel//Desktop", 0, win32con.KEY_SET_VALUE) # 在注冊表中寫入屬性值 win32api.RegSetValueEx(k, "wapaperStyle", 0, win32con.REG_SZ,"2") # 0 代表桌面居中 2 代表拉伸桌面 win32api.RegSetValueEx(k, "Tilewallpaper", 0, win32con.REG_SZ,"0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, paper_path, win32con.SPIF_SENDWININICHANGE) # 刷新桌面
然后就是從已經下載的壁紙當中選擇圖片
def change_wallpaper(): pic_list = os.listdir("wallpaper") # 得到文件路徑下的圖片,列表類型 i=0 print(pic_list) while True: pic = "wallpaper"+'/{}'.format(pic_list[i]) abspath_pic = os.path.abspath(pic) windows_img(abspath_pic) print(abspath_pic) time.sleep(1000) # 設置壁紙更換間隔 i += 1 if i==len(pic_list): # 如果是最后一張圖片,則重新到第一張 i=0if __name__ == '__main__': change_wallpaper()
這樣一個簡單的自動切換桌面壁紙的工具就完成了,快來嘗試一下吧!
本文鏈接:http://www.tebozhan.com/showinfo-26-17559-0.html用Python下載壁紙并自動更換桌面
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com