Python實現(xiàn)愛心彈窗的完整教學(附源碼)
一段不到 40 行的 Python 代碼,在屏幕上依次綻放出愛心形狀的彈窗,每一條都是你想對 TA 說的話。
效果預覽

程序運行后會出現(xiàn)三個階段:
- 愛心綻放 — 100 個小彈窗沿心形曲線依次彈出,每 0.03 秒一個,最終拼成一顆完整的愛心。
- 滿屏暴擊 — 愛心消失后,彈窗鋪滿整個屏幕,每個窗口都是一句暖心的叮囑。
- 溫柔收場 — 等待 10 秒后,所有彈窗在 1 秒內(nèi)優(yōu)雅地逐個關閉。
按下 空格鍵 可以隨時退出。
核心原理
1. 心形曲線公式
愛心形狀來自經(jīng)典的參數(shù)方程:
- x=16sin3(t)
- y=13cos(t)−5cos(2t)−2cos(3t)−cos(4t)
將參數(shù) t 從 0 到 2π 均勻取 100 個點,就能得到一個平滑的心形輪廓。然后將其縮放并居中到屏幕中央。
def heart_points(n, screen_w, screen_h):
points = []
for i in range(n):
t = i / n * 2 * math.pi
x = 16 * math.sin(t) ** 3
y = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
sx = int(screen_w/2 + x*20 - 50) # 縮放 20 倍并居中
sy = int(screen_h/2 - y*20 - 80)
points.append((sx, sy))
return points
2. 彈窗窗口
每個彈窗本質(zhì)上是一個 tk.Toplevel 小窗口:
def create_window(x, y, tip=None):
win = tk.Toplevel()
win.geometry(f"150x60+{x}+{y}")
win.title("提示")
win.attributes('-topmost', 1) # 始終置頂
text = tip or random.choice(tips) # 隨機選取一句暖心話
color = random.choice(colors) # 隨機背景色
tk.Label(win, text=text, bg=color,
font=("微軟雅黑", 14), width=20, height=3).pack()
return win
-topmost:確保彈窗始終在最前方。- 隨機文案:每次從預設列表中隨機抽取一條溫馨提醒。
- 隨機配色:粉色、淺藍、淺綠等柔和色調(diào),視覺上溫馨可愛。
3. 三階段動畫流程
# 階段一:愛心綻放
for x, y in heart_points(100, sw, sh):
win = create_window(x, y)
hearts.append(win)
root.update()
time.sleep(0.03)
time.sleep(1)
# 銷毀愛心彈窗
# 階段二:滿屏暴擊
for _ in range(sw//150 * sh//40 + 50):
x = random.randint(0, sw-150)
y = random.randint(0, sh-60)
win = create_window(x, y)
all_windows.append(win)
root.update()
time.sleep(0.005)
time.sleep(10)
# 階段三:優(yōu)雅關閉
interval = 1.0 / len(all_windows)
for win in all_windows:
win.destroy()
root.update()
time.sleep(interval)
完整代碼(可讀版)
import tkinter as tk, random, time, sys, math
hearts, all_wins = [], []
tips = ["多喝水利", "好好愛自己", "好好吃飯", "保持好心情",
"我想你了", "順順利利", "別熬夜", "天涼了多穿衣服"]
colors = ["pink", "lightblue", "lightgreen", "lemonchiffon",
"hotpink", "skyblue"]
def heart_points(n, screen_w, screen_h):
"""生成心形曲線上的 n 個屏幕坐標點"""
points = []
for i in range(n):
t = i / n * 2 * math.pi
x = 16 * math.sin(t) ** 3
y = (13 * math.cos(t) - 5 * math.cos(2*t)
- 2 * math.cos(3*t) - math.cos(4*t))
sx = int(screen_w / 2 + x * 20 - 50)
sy = int(screen_h / 2 - y * 20 - 80)
sx = max(0, min(sx, screen_w - 150))
sy = max(0, min(sy, screen_h - 60))
points.append((sx, sy))
return points
def create_popup(x, y, tip=None):
"""在指定位置創(chuàng)建一個彈窗"""
win = tk.Toplevel()
win.geometry(f"150x60+{x}+{y}")
win.title("提示")
win.attributes('-topmost', 1)
text = tip or random.choice(tips)
bg = random.choice(colors)
tk.Label(win, text=text, bg=bg,
font=("微軟雅黑", 14), width=20, height=3).pack()
win.bind('<space>',
lambda e: [w.destroy() for w in hearts + all_wins] or sys.exit())
return win
def main():
root = tk.Tk()
root.withdraw()
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
# ---- 階段一:愛心綻放 ----
points = heart_points(100, sw, sh)
for i, (x, y) in enumerate(points):
tip = "充實自己" if i == len(points) - 1 else None
win = create_popup(x, y, tip)
hearts.append(win)
root.update()
time.sleep(0.03)
time.sleep(1)
for w in hearts:
if isinstance(w, tk.Toplevel) and w.winfo_exists():
w.destroy()
# ---- 階段二:滿屏暴擊 ----
count = sw // 150 * sh // 40 + 50
for _ in range(count):
x = random.randint(0, sw - 150)
y = random.randint(0, sh - 60)
win = create_popup(x, y)
all_wins.append(win)
root.update()
time.sleep(0.005)
time.sleep(10)
# ---- 階段三:優(yōu)雅關閉 ----
interval = 1.0 / len(all_wins) if all_wins else 0
for win in all_wins:
if isinstance(win, tk.Toplevel) and win.winfo_exists():
win.destroy()
root.update()
time.sleep(interval)
root.mainloop()
if __name__ == "__main__":
main()
自定義指南
修改文案
編輯 tips 列表即可替換彈窗中顯示的文字:
tips = ["自定義文案1", "自定義文案2", "..."]
修改配色
編輯 colors 列表,支持所有 Tkinter 認可的顏色名或十六進制值:
colors = ["#FFB6C1", "#87CEEB", "#DDA0DD", "#98FB98"]
調(diào)整愛心大小
修改 heart_points 函數(shù)中 x * 20 和 y * 20 的縮放倍數(shù),數(shù)字越大愛心越大。
調(diào)整彈窗數(shù)量
- 愛心彈窗數(shù):修改
heart_points(100, ...)中的100 - 滿屏彈窗數(shù):修改
sw // 150 * sh // 40 + 50中的公式
運行方式
確保已安裝 Python 3(自帶 tkinter),直接運行:
python 愛心彈窗.py
僅依賴 Python 標準庫,無需安裝任何第三方包。
小結(jié)
這個小程序用到的知識點:
| 知識點 | 說明 |
|---|---|
| tkinter | Python 標準 GUI 庫 |
| 心形參數(shù)方程 | 數(shù)學之美 |
| time.sleep + update() | 手動實現(xiàn)逐幀動畫 |
| random.choice | 隨機選取文案和顏色 |
| -topmost 屬性 | 窗口始終置頂 |
不到 40 行代碼,就能給 TA 一個小小的驚喜??烊ピ囋嚢?!
以上就是Python實現(xiàn)愛心彈窗的完整教學(附源碼)的詳細內(nèi)容,更多關于Python愛心彈窗的資料請關注腳本之家其它相關文章!
相關文章
Python大數(shù)據(jù)之從網(wǎng)頁上爬取數(shù)據(jù)的方法詳解
這篇文章主要介紹了Python大數(shù)據(jù)之從網(wǎng)頁上爬取數(shù)據(jù)的方法,結(jié)合實例形式詳細分析了Python爬蟲爬取網(wǎng)頁數(shù)據(jù)的相關操作技巧,需要的朋友可以參考下2019-11-11

