Python与Windows桌面

Python更换windows桌面

前言

每天下班,有时候会留下一些事情需要明天更进
为了防止忘记,之前会写在txt里面
image
就算txt放在显眼的位置,有时候还是会忘记
所以想要将文本输出到桌面壁纸上,加粗高亮,这样就不会忘了

准备工作

有一些库的下载可能会很慢,所以推荐使用阿里云镜像
对于网络好的用户,这一步可以跳过

升级pip版本

python -m pip install --upgrade pip

设置阿里云镜像

pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/

取消使用阿里云镜像

pip config unset global.index-url

代码

Python官方文档
https://docs.python.org/3/library/ctypes.html
ctypes是 Python 的外部函数库。它提供 C 兼容的数据类型,并允许调用 DLL 或共享库中的函数。它可用于将这些库包装在纯 Python 中。

pip install pillow
import ctypes

from PIL import Image, ImageFont, ImageDraw


def change_wallpaper():
    # path 桌面壁纸路径
    path = "C:\Windows\Web\Wallpaper\Theme1\img2.jpg"

    img = Image.open(path)

    # 选择字体样式 大小 颜色
    font = ImageFont.truetype("C:\Windows\Fonts\msyh.ttc", 120)
    color = (66, 66, 66)

    # txt_path txt文件位置 我放在桌面 r表示不认为\为转义符
    txt_path = r"C:\Users\Zzz\Desktop\rember.txt"

    # 记录txt中内容 放在list中
    word = []
    with open(txt_path, encoding='utf-8') as file:
        for line in file.readlines():
            word.append(line)

    draw = ImageDraw.Draw(img)
    width = img.width
    fixed_with = width / 5
    total = 1

    # fixed_with 文字所在x轴起始位置
    for message in word:
        start_height = 100

        # changed_height 文字所在y轴高度
        # 155 : 文字之间间隔 可以参考font字体大小
        changed_height = start_height + total * 155

        # 将txt中文字写入图片 x,y轴位置
        position = (fixed_with, changed_height)
        draw.text(position, message, color, font=font)

        # 写一行 空一行
        position = (fixed_with, changed_height + 155)
        draw.text(position, "", color, font=font)
        total = total + 2

    # file_name 生成图片存放位置
    file_name = r"C:\Users\Zzz\Desktop\background.png"
    img.save(file_name)

    # 设置壁纸
    ctypes.windll.user32.SystemParametersInfoW(20, 0, file_name, 0)  # 设置桌面壁纸


if __name__ == '__main__':
    change_wallpaper()

效果展示

  • 文档中信息
    image
  • 壁纸效果
    image

Tips-如何更有仪式感

  1. 桌面上新建一个txt
    image
  2. 写入两行脚本
cmd /c python D:\a_projects\python\day_1\com\lizi\background.py
del C:\Users\Zzz\Desktop\background.png

cmd /c : 打开cmd窗口 运行完关闭
python D:\a_projects\python\day_1\com\lizi\background.py :用python执行文件
del C:\Users\Zzz\Desktop\background.png : 删除生成的图片
3. 将txt后缀 改为bat
image

每天更新完rember.txt后 双击bat脚本 就能自动替换桌面壁纸了

posted @ 2022-03-03 23:36  异世界阿伟  阅读(320)  评论(0编辑  收藏  举报