多彩编程 多彩编程MZPH · CODE BLOG
ARTICLE DETAIL

文章详情

深耕前端与后端开发技术的一线实战笔记与踩坑复盘。

爱心代码-表白专属(CV可用)

爱心代码-表白专属(CV可用) 一.简介这是一个tkinter 桌面弹窗小程序表白先在屏幕上用 100 个小弹窗拼出一个爱心然后满屏随机弹窗轰炸最后自动收场。运行中按空格或 Esc 可随时退出。二.核心原理爱心参数方程x 16·sin³(θ) y 13·cos(θ) − 5·cos(2θ) − 2·cos(3θ) − cos(4θ)经典的心形曲线取 θ ∈ [0, 2π) 均匀采样 100 个点再经过×20缩放 屏幕中心偏移y 轴取负是因为屏幕坐标向下为正每个点变成一个 150×60 的置顶弹窗。三.执行流程四.代码import tkinter as tk import random import math # 可自行修改的配置 # 暖心文案库 MESSAGES [最喜欢小x了, 好好爱自己哦, 小x好好吃饭哦, 保持好心情, 我想你了小x, 顺顺利利, 别熬夜, 天凉了多穿衣服] # 弹窗背景色 COLORS [pink, lightblue, lightgreen, lemonchiffon, hotpink, skyblue] # 爱心窗口数量 HEART_COUNT 100 # 满屏弹窗数量 POPUP_COUNT 400 # 专属文案爱心最后一个窗口显示 SPECIAL_TIP 我想小x啦 heart_windows [] popup_windows [] def heart_points(n, screen_w, screen_h): 生成爱心轮廓的坐标点经典爱心参数方程 points [] for i in range(n): th i / n * 2 * math.pi x 16 * math.sin(th) ** 3 y 13 * math.cos(th) - 5 * math.cos(2 * th) - 2 * math.cos(3 * th) - math.cos(4 * th) # 坐标适配屏幕避免窗口超出屏幕 sx int(screen_w / 2 x * 20 - 50) sy int(screen_h / 2 - y * 20 - 80) points.append((max(0, min(sx, screen_w - 150)), max(0, min(sy, screen_h - 60)))) return points def create_popup(root, x, y, tipNone): 创建单个弹窗窗口 win tk.Toplevel(root) win.geometry(f150x60{x}{y}) win.title(提示) win.attributes(-topmost, 1) # wraplength 自动换行避免文案超出窗口被裁切 tk.Label(win, texttip or random.choice(MESSAGES), bgrandom.choice(COLORS), font(微软雅黑, 11), wraplength140, padx8, pady8 ).pack(fillboth, expandTrue) return win def safe_destroy(win): 安全销毁窗口 try: if isinstance(win, tk.Toplevel) and win.winfo_exists(): win.destroy() except tk.TclError: pass def main(): root tk.Tk() root.withdraw() # 隐藏主窗口仅显示弹窗 root.title(弹窗爱心) # bind_all 绑定在根窗口任意弹窗持有焦点时按空格都能退出 root.bind_all(space, lambda e: root.destroy()) root.bind_all(Escape, lambda e: root.destroy()) # 兜底Esc 也能退出 screen_w root.winfo_screenwidth() screen_h root.winfo_screenheight() heart_pts heart_points(HEART_COUNT, screen_w, screen_h) # ---------- 阶段1爱心弹窗逐个出现每 30ms 一个 ---------- def spawn_heart(i0): if i HEART_COUNT: root.after(1000, destroy_heart) # 爱心成型后停留 1 秒 return tip SPECIAL_TIP if i HEART_COUNT - 1 else None heart_windows.append(create_popup(root, *heart_pts[i], tip)) root.after(30, spawn_heart, i 1) # ---------- 阶段2销毁爱心 ---------- def destroy_heart(): for win in heart_windows: safe_destroy(win) heart_windows.clear() root.after(100, spawn_popup, 0) # ---------- 阶段3满屏随机弹窗每 5ms 一个 ---------- def spawn_popup(i0): if i POPUP_COUNT: root.after(5000, close_popups) # 满屏停留 5 秒 return x random.randint(0, screen_w - 150) y random.randint(0, screen_h - 60) popup_windows.append(create_popup(root, x, y)) root.after(5, spawn_popup, i 1) # ---------- 阶段41 秒内依次关闭全部弹窗 ---------- def close_popups(): if popup_windows: safe_destroy(popup_windows.pop(0)) root.after(max(1, 1000 // POPUP_COUNT), close_popups) else: root.after(500, root.destroy) # 全部结束后正常退出不再挂起 root.after(300, spawn_heart) root.mainloop() # 事件驱动等待/停留期间按空格随时可退出 if __name__ __main__: main()五.效果图
返回列表