简介

今天给大家分享一个用 Python + Tkinter 制作的桌面小程序,它可以在屏幕上自动显示温馨文字,如“好好吃饭”“注意保暖”“保持微笑”等,并配合背景音乐和炫彩动画,让你的桌面充满温暖气息。

这个程序适合想要在工作或学习时获得温馨提示的人,也可以作为一个有趣的小项目学习 Tkinter 动画、文字绘制、线程和背景音乐的整合。


功能亮点

  1. 自动文字显示

    • 随机出现温馨文字,文字带圆角背景

    • 背景颜色和文字颜色随机生成,避免重复和冲突

    • 文字大小自适应背景框,显示美观

  2. 中央主文字动画

    • 显示主要提示文字,如“记得好好爱自己!”

    • 文字带渐变发光和呼吸缩放效果

  3. 背景音乐

    • 支持播放 mp3 音乐

    • 音乐与文字动画同步,提升桌面温暖氛围

    • 注意:音乐文件需与程序放在同级目录

  4. 易于使用

    • 双击运行即可,全屏显示

    • 配置文件可自定义文字列表、字体、颜色、动画参数

    • 支持 Windows 系统


技术实现

  • Tkinter:用于绘制文字、背景框及动画效果

  • 线程:让文字动画和主流程并行运行,不卡顿

  • Python:代码可修改扩展,方便自定义

  • pygame:用于播放背景音乐


使用方法

  1. 下载程序和配置文件到同一个目录

  2. 将背景音乐文件 bgm.mp3 放在同级目录

  3. 双击运行 exe 文件即可看到文字动画和背景音乐

  4. 可通过修改 config.json 自定义文字、字体、颜色和动画参数


适用场景

  • 办公桌面提醒,温暖自己或同事

  • 学习、工作环境中的轻松提示

  • Python 学习者用作 Tkinter 动画和多线程练习项目


总结

这是一个简单有趣的桌面小程序,结合了文字动画、颜色搭配和背景音乐,可以让桌面更生动、温暖,也可以作为 Python 小项目学习的案例。

源代码

import tkinter as tk
import random, time, json, threading, math
import pygame

# ================== 配置 ==================
with open("config.json", "r", encoding="utf-8") as f:
    config = json.load(f)

texts = config["texts"]
main_text = config["main_text"]
music_path = config["music_path"]
run_time = config["run_time"]
colors = config["color_palette"]
font_family = config["font_family"]
font_min, font_max = config["font_size_range"]
explosion_power = config.get("explosion_power", 40)
bg_color_palette = config.get("color_palette", ["#222222", "#333333", "#444444", "#555555"])
main_base_color = config.get("main_base_color", [255, 215, 0])  # 金色 RGB

# 文字背景固定大小 & 圆角
bg_width = 160
bg_height = 60
corner_radius = 12

# ================== 初始化窗口 ==================
root = tk.Tk()
root.attributes("-fullscreen", True)
root.configure(bg="#000000")#背景颜色
screen_w = root.winfo_screenwidth()
screen_h = root.winfo_screenheight()
canvas = tk.Canvas(root, bg="#000000", highlightthickness=0)
canvas.pack(fill="both", expand=True)

# ================== 初始化音乐 ==================
pygame.mixer.init()
pygame.mixer.music.load(music_path)
pygame.mixer.music.play(-1)

# ================== 圆角矩形函数 ==================
def create_rounded_rect(canvas, x1, y1, x2, y2, radius=10, **kwargs):
    points = [
        x1+radius, y1,
        x2-radius, y1,
        x2, y1,
        x2, y1+radius,
        x2, y2-radius,
        x2, y2,
        x2-radius, y2,
        x1+radius, y2,
        x1, y2,
        x1, y2-radius,
        x1, y1+radius,
        x1, y1
    ]
    return canvas.create_polygon(points, smooth=True, **kwargs)

# ================== 文字类 ==================
class FloatingText:
    def __init__(self, text):
        self.text = text

        # 背景颜色随机
        self.bg_color = random.choice(bg_color_palette)

        # 文字颜色随机,但避免与背景颜色相同
        possible_colors = [c for c in config["text_color_palette"] if c != self.bg_color]
        self.color = random.choice(possible_colors) if possible_colors else "black"

        # 随机位置
        self.x = random.randint(100, screen_w - 100)
        self.y = random.randint(100, screen_h - 100)

        # 动态调整字体大小以适配背景
        # 假设文字宽度不超过背景宽度的80%,高度不超过背景高度的80%
        test_size = font_max
        while test_size > font_min:
            temp_id = canvas.create_text(0, 0, text=self.text, font=(font_family, test_size, "bold"))
            bbox = canvas.bbox(temp_id)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]
            canvas.delete(temp_id)
            if text_width <= bg_width * 0.8 and text_height <= bg_height * 0.8:
                break
            test_size -= 1
        self.size = test_size

        # 创建文字
        self.id = canvas.create_text(self.x, self.y, text=self.text,
                                     font=(font_family, self.size, "bold"), fill=self.color)

        # 创建固定大小圆角背景
        self.bg_id = create_rounded_rect(canvas,
                                         self.x - bg_width//2, self.y - bg_height//2,
                                         self.x + bg_width//2, self.y + bg_height//2,
                                         radius=corner_radius, fill=self.bg_color, outline="")

        canvas.tag_raise(self.id, self.bg_id)

    def move_in(self):
        pass  # 文字已直接出现,不再移动

    def move_toward_center(self, cx, cy):
        for _ in range(40):
            self.x += (cx - self.x) * 0.08
            self.y += (cy - self.y) * 0.08
            canvas.coords(self.id, self.x, self.y)
            canvas.coords(self.bg_id,
                          self.x - bg_width//2, self.y - bg_height//2,
                          self.x + bg_width//2, self.y + bg_height//2)
            time.sleep(0.01)

    def explode(self):
        angle = random.uniform(0, 2*math.pi)
        speed = random.uniform(explosion_power, explosion_power*1.5)
        vx = speed * math.cos(angle)
        vy = speed * math.sin(angle)
        for _ in range(80):
            self.x += vx
            self.y += vy
            canvas.coords(self.id, self.x, self.y)
            canvas.coords(self.bg_id,
                          self.x - bg_width//2, self.y - bg_height//2,
                          self.x + bg_width//2, self.y + bg_height//2)
            if self.x < -300 or self.x > screen_w+300 or self.y < -300 or self.y > screen_h+300:
                break
            time.sleep(0.005)
        canvas.delete(self.id)
        canvas.delete(self.bg_id)

# ================== 主动画流程 ==================
labels = []

def create_random_text():
    total = len(texts) * 4
    start_delay = 0.1  # 初始间隔
    end_delay = 0  # 最小间隔
    for i in range(total):
        t = FloatingText(random.choice(texts))
        labels.append(t)
        # 使用立方加速公式
        progress = i / total
        delay = start_delay * (1 - progress**5) + end_delay * progress**5
        time.sleep(delay)



def gather_and_explode():
    time.sleep(1)
    cx, cy = screen_w//2, screen_h//2
    for t in labels:
        threading.Thread(target=t.move_toward_center, args=(cx, cy), daemon=True).start()
    time.sleep(1)
    for t in labels:
        threading.Thread(target=t.explode, daemon=True).start()
    show_main_text()

# ================== 中央主文字渐变发光 + 呼吸 ==================
def show_main_text():
    cx, cy = screen_w//2, screen_h//2
    size = 120
    text_id = canvas.create_text(cx, cy, text=main_text, font=(font_family, size, "bold"), fill="#FFD700")
    step = 0

    def gradient_flash():
        nonlocal step
        r = max(0, min(255, int(main_base_color[0] + 40 * math.sin(step * 0.2))))
        g = max(0, min(255, int(main_base_color[1] + 40 * math.sin(step * 0.2))))
        b = max(0, min(255, int(main_base_color[2] + 40 * math.sin(step * 0.2))))
        color_hex = f"#{r:02x}{g:02x}{b:02x}"
        canvas.itemconfig(text_id, fill=color_hex)
        scale = 1 + 0.02 * math.sin(step * 0.3)
        canvas.scale(text_id, cx, cy, scale, scale)
        step += 1
        canvas.after(50, gradient_flash)

    gradient_flash()

# ================== 主控制线程 ==================
def main_flow():
    create_random_text()
    gather_and_explode()
    time.sleep(run_time)
    pygame.mixer.music.stop()
    root.destroy()

threading.Thread(target=main_flow, daemon=True).start()
root.mainloop()

已经打包,打包地址,需要自取

通过网盘分享的文件:dist.rar

链接: https://pan.baidu.com/s/1LcFtKU820i48GoD7po6kBw?pwd=xm2u 提取码: xm2u

--来自百度网盘超级会员v2的分享

我用夸克网盘给你分享了「dist.rar」,点击链接或复制整段内容,打开「夸克APP」即可获取。

/~020d38wkFV~:/

链接:https://pan.quark.cn/s/14011a65d7ab

提取码:YhkX

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐