python making wallpaper replacement program

Posted by m3rajk on Fri, 04 Oct 2019 01:31:02 +0200

I. Brief Introduction of Functions

1. Use reptile technology to climb up pictures from the network
 2. Converting Pictures to. bmp Extension Type Pictures
 3. Set Pictures to Desktop Wallpaper
 4. Packaging into exe
 5. Modify registry to create right-click shortcuts
 6. Make the uninstall program, delete the downloaded image, delete the right-click shortcut

2. Start making

Paste code directly, annotate or mark in code!!!

1. request module: using requests can simulate browser requests. Compared with urllib, the api of requests module is more convenient (essentially encapsulating urllib3).
2. PIL module: It is the de facto image processing standard library of Python platform. It supports multiple formats and provides powerful graphics and image processing functions.
3. pywin32 is a third-party module library. Its main function is to facilitate python developers to call a module library of windows API quickly.

Note that pypiwin32 is installed here because pywin32 imports are installed
import win32api, import win32con, import win32gui will appear red line, suggesting that the corresponding module can not be found. (I don't know why, so I modified pypiwin32, I hope there is a big guy pointing out).

# encoding: utf-8
# PIP install requests -- request installation command
import requests #
import json
import random
import os, sys
import ctypes
# Pip install pillow -- PIL installation command
from PIL import Image
# Pip install pypiwin32 - Win32 api, Win32 con, Win32 GUI installation commands
import win32api
import win32con
import win32gui

# Download pictures
def download_picture():
    search_url = 'https://unsplash.com/napi/search?client_id=%s&query=%s&page=1'
    client_id = 'fa60305aa82e74134cabc7093ef54c8e2c370c47e73152f72371c828daedfcd7'
    categories = ['nature', 'flowers', 'wallpaper', 'landscape', 'sky']
    search_url = search_url % (client_id, random.choice(categories))
    response = requests.get(search_url)

	# Converting characters in json format to dict
    data = json.loads(response.text)
    results = data['photos']['results']
    # Screening images with aspect ratio greater than or equal to 1.33 by filter
    results = list(filter(lambda x: float(x['width']) / x['height'] >= 1.33, results))
    # random.choice(results) Random access to an image address
    result = random.choice(results)
    result_id = str(result['id'])
    result_url = result['urls']['regular']
    # The above contents are written differently according to different websites, mainly to get the address of the picture.

    root = 'D:\\wallpaper\\'  # Save Picture Path
    if not os.path.exists(root):
        os.mkdir(root)
    jpg_file = root + result_id + '.jpg'
    bmp_file = root + result_id + '.bmp'
    r = requests.get(result_url)
    r.raise_for_status()
    with open(jpg_file, 'wb') as file:
        file.write(r.content)
    img = Image.open(jpg_file)
    img.save(bmp_file, 'BMP')
    # Delete jpg files
    os.remove(jpg_file)

    return bmp_file


def replace_wallpaper():
    bmp_file = download_picture()
    # The format of wallpaper pictures must be BMP (but when I tested, there was no such restriction! Successful formatting as long as it is in general format)
    # Method 1: 
    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
    # 2: Stretching adapts to desktop; 0: desktop centered
    win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp_file, 1 + 2)
    # Close the open key
    win32api.RegCloseKey(key)
    # Method two: 
    # ctypes.windll.user32.SystemParametersInfoW(20, 0, bmpFile, 0)  # Setting Desktop Wallpaper

# Operate registry to create right-click shortcuts
def set_reg():
    # full_path = sys.argv[0]
    # Get the path of the exe file itself
    full_path = sys.executable
    reg_root = win32con.HKEY_CLASSES_ROOT
    # Key path (specific path self-modifying)
    reg_path = "Directory\\Background\\shell\\wallpaper"
    reg_path_children = reg_path + "\\command"
    # Permissions and parameter settings
    reg_flags = win32con.WRITE_OWNER | win32con.KEY_WOW64_64KEY | win32con.KEY_ALL_ACCESS
    try:
        # Determine whether a key exists in the registry
        key = win32api.RegOpenKeyEx(reg_root, reg_path, 0, reg_flags)
    except Exception as e:
        print(e)
        key = None
    key_flag = False
    if key is None:
        key_flag = True
    else:
        key_flag = False
        win32api.RegCloseKey(key)
    if key_flag:
        try:
        	# Maybe someone thinks the above judgment key is superfluous. I am also a novice. I think it will be better to judge.
            # Create directly (get if present)
            # Create the parent wallpaper
            key, _ = win32api.RegCreateKeyEx(reg_root, reg_path, reg_flags)
            win32api.RegSetValueEx(key, '', 0, win32con.REG_SZ, 'change wallpaper')
            win32api.RegSetValueEx(key, 'Icon', 0, win32con.REG_SZ, full_path)
            win32api.RegCloseKey(key)
            # Create subitem command
            key, _ = win32api.RegCreateKeyEx(reg_root, reg_path_children, reg_flags)
            win32api.RegSetValueEx(key, '', 0, win32con.REG_SZ, full_path)
            win32api.RegCloseKey(key)
        except Exception as e:
            win32api.RegCloseKey(key)
            ctypes.windll.user32.MessageBoxW(0, 'Settings failed, why ah!!!', 'Right-click shortcut menu settings (wallpaper replacement)', 0)
    else:
        key, _ = win32api.RegCreateKeyEx(reg_root, reg_path_children, reg_flags)
        win32api.RegSetValueEx(key, '', 0, win32con.REG_SZ, full_path)
        win32api.RegCloseKey(key)


if __name__ == "__main__":
    replace_wallpaper()
    set_reg()
# pyinstaller -w -F -i blueWhaleLogo15.ico wallpaper.py

Uninstall program

Annotations have time to add back

# encoding: utf-8
import os, sys
# pywin32
import win32api
import win32con
# pip install pygubu
from tkinter import *
import ctypes


def delete_picture(root):
    try:
        ls = os.listdir(root)
        ls_length = len(ls)
        if ls_length == 0:
            os.rmdir(root)
        else:
            for i in ls:
                c_path = os.path.join(root, i)
                if os.path.isdir(c_path):
                    delete_picture(c_path)
                else:
                    os.remove(c_path)
        os.rmdir(root)
    except Exception as e:
        print(e)


def delete_reg():
    reg_root = win32con.HKEY_CLASSES_ROOT
    # Key path (specific path self-modifying)
    reg_path = "Directory\\Background\\shell\\wallpaper\\command"
    # Permissions and parameter settings
    reg_flags = win32con.WRITE_OWNER | win32con.KEY_WOW64_64KEY | win32con.KEY_ALL_ACCESS
    try:
        # Determine whether a key exists in the registry
        key = win32api.RegOpenKeyEx(reg_root, reg_path, 0, reg_flags)
    except Exception as e:
        print(e)
        key = None
    key_flag = False
    if key is None:
        key_flag = False
    else:
        key_flag = True
        win32api.RegCloseKey(key)
    if key_flag:
        try:
            # Delete values (key s also have close methods, you can use the with structure)
            # with win32api.RegOpenKeyEx(reg_root, reg_path, 0, reg_flags) as key:
            #     win32api.RegDeleteValue(key, 'test_value')
            # Delete keys (you need to get their parent keys and delete the child keys through the parent keys)
            reg_parent, subkey_name = os.path.split(reg_path)
            try:
                key2 = win32api.RegOpenKeyEx(reg_root, reg_parent, 0, reg_flags)
            except Exception as e:
                print(e)
                key2 = None
            key_flag2 = False
            if key2 is None:
                key_flag2 = False
            else:
                key_flag2 = True
            if key_flag2:
                win32api.RegDeleteKeyEx(key2, subkey_name)
                win32api.RegCloseKey(key2)
                reg_parent2, subkey_name2 = os.path.split(reg_parent)
                try:
                    key3 = win32api.RegOpenKeyEx(reg_root, reg_parent2, 0, reg_flags)
                except Exception as e:
                    print(e)
                    key3 = None
                key_flag3 = False
                if key3 is None:
                    key_flag3 = False
                else:
                    key_flag3 = True
                if key_flag3:
                    win32api.RegDeleteKeyEx(key3, subkey_name2)
                    win32api.RegCloseKey(key3)
                else:
                    win32api.RegCloseKey(key3)
                    pass
            else:
                pass
        except Exception as e:
            print(e)
            sys.exit()


if __name__ == "__main__":
    delete_reg()
    delete_picture('D:\\wallpaper\\')
    ctypes.windll.user32.MessageBoxW(0, 'Delete successful', 'Right-click shortcut menu settings (wallpaper replacement)', 0)
# pyinstaller -w -F -i blueWhaleLogo15.ico unwallpaper.py

Topics: pip JSON Python encoding