)
一.簡介這是一個tkinter 桌面彈窗小程序表白先在屏幕上用 100 個小彈窗拼出一個愛心然后滿屏隨機彈窗轟炸最后自動收場。運行中按空格或 Esc 可隨時退出。二.核心原理愛心參數方程x 16·sin3(θ) 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()五.效果圖