Python 将土味情话语录设置为桌面壁纸

每天学一句,单身远离我!

 

import os
import tempfile
import time
import requests
import win32api
import win32con
import win32gui
from PIL import Image, ImageDraw, ImageFont
import random

def setWallPaper(pic):
    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拉伸适应桌面,0桌面居中
    win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, pic, 1 + 2)
    print('成功应用桌面壁纸')

def love():
    url = r'https://api.vvhan.com/api/love'
    res = requests.get(url).text
    content = "『{}』".format(res)
    return content

def love2():
    url = r'https://api.lovelive.tools/api/SweetNothings/WebSite'
    res = requests.get(url).text
    content = "『{}』".format(res)
    return content

def hitokoto():
    url = 'https://v1.hitokoto.cn/'
    res = requests.get(url).json()
    hitokoto = res['hitokoto'].strip('。')
    from_where = res['from']
    from_who = res['from_who']
    content = "『{}』".format(hitokoto)
    return content

def word():
    global word_type
    if word_type == '0':
        return hitokoto()
    elif word_type == '1':
        return random.choice([love(), love2()])


def jpg(path):
    if not os.path.exists(path):
        url = 'https://cn-south-227-storage-hitokoto-19627663.oss.dogecdn.com/pic/qf3cu.jpg'
        content = requests.get(url).content
        with open(path, 'wb+') as f:
            f.write(content)

# 语录类型
word_type = 0
# 临时目录
root_path = tempfile.gettempdir()
# 背景图片路径
bgfile = os.path.join(root_path, "bg.jpg")
# 最终的壁纸图片路径
wallfile = os.path.join(root_path, "wall.jpg")
def main():
    # 下载背景图
    jpg(bgfile)
    # 打开背景图
    img = Image.open(bgfile)
    # 创建空白图
    d = ImageDraw.Draw(img)
    # 设置字体
    font = ImageFont.truetype("simhei.ttf", 60, encoding="utf-8")
    width, height = img.size
    length = 99
    one_word = ""
    # 确保语录不超过壁纸宽度
    while (length > width//60):
        # 获取语录
        one_word = word()
        length = len(one_word)
        time.sleep(1)
    print(one_word)
    # 语录添加到图片
    d.text((width / 2 - 30 * (len(one_word)), height / 2 - 240), one_word, font=font, fill=(80, 80, 80, 128))
    # 报错图片
    img.save(wallfile)
    # 关闭流
    img.close()
    # 设置壁纸
    setWallPaper(wallfile)
    # 删除壁纸图片
    os.unlink(wallfile)
    # 删除背景图片
    # os.unlink(bgfile)


if __name__ == '__main__':
    word_type = input('>> 类型(0:一言; 1:情话):').strip()
    while True:
        main()
        time.sleep(5)



 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小锋学长生活大爆炸

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

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

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

打赏作者

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

抵扣说明:

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

余额充值