Python turtle打造一個浪漫流星雨表白程序
大家好!今天分享一個用 Python 標準庫(turtle + tkinter)實現(xiàn)的浪漫表白程序。點擊"好哦"后,80顆流星劃過夜空,每一顆都是獨一無二的隨機生成;點擊"不要"或關(guān)閉窗口?不存在的!這是一個"霸道總裁式"的表白神器
效果預(yù)覽
程序啟動后彈出一個居中窗口,上面寫著"親愛的,做我女朋友好嗎?"。兩個按鈕:“好哦"和"不要”。

- 點擊 “好哦” → 窗口關(guān)閉,全屏進入流星雨動畫
- 點擊 “不要” → 彈出警告框"再給你一次機會!"
- 點擊 關(guān)閉按鈕 → 彈出警告框"逃避是沒有用的哦"
流星雨效果:黑色夜空中,80顆藍白色流星從左上向右下劃過,每顆流星形狀、大小、速度、顏色各不相同,循環(huán)往復(fù)……

技術(shù)棧
| 技術(shù) | 說明 |
|---|---|
| turtle | Python 內(nèi)置圖形庫,繪制流星形狀 |
| tkinter | Python 內(nèi)置 GUI 庫,彈窗表白界面 |
| random | 隨機生成流星參數(shù) |
| math | 三角函數(shù)計算流星弧度 |
純標準庫,無需 pip 安裝任何第三方包,開箱即用!
項目結(jié)構(gòu)
流星雨表白/ ├── 流星雨.py # 主程序(完整單文件) └── README.md
核心功能拆解
tkinter 彈窗 —— "霸道總裁"式表白
import tkinter as tk
def love():
root = tk.Tk()
root.title('?')
root.resizable(0, 0) # 禁止調(diào)整窗口大小
root.wm_attributes("-toolwindow", 1) # 隱藏任務(wù)欄按鈕
# 計算居中位置
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
widths, heights = 300, 100
x = (screenwidth - widths) / 2
y = (screenheight - heights) / 2
root.geometry('%dx%d+%d+%d' % (widths, heights, x, y))
# 表白文字
tk.Label(root, text='親愛的,做我女朋友好嗎?',
width=37, font=('宋體', 12)).place(x=0, y=10)
# 按鈕
tk.Button(root, text='好哦', width=5, height=1, command=OK).place(x=80, y=50)
tk.Button(root, text='不要', width=5, height=1, command=NO).place(x=160, y=50)
# 綁定關(guān)閉事件
root.protocol('WM_DELETE_WINDOW', closeWindow)
root.mainloop()
關(guān)鍵技巧:
| 技巧 | 代碼 | 效果 |
|---|---|---|
| 窗口居中 | geometry('%dx%d+%d+%d') | 彈窗出現(xiàn)在屏幕正中央 |
| 禁止關(guān)閉 | protocol('WM_DELETE_WINDOW', closeWindow) | 攔截右上角關(guān)閉按鈕 |
| 隱藏任務(wù)欄 | wm_attributes("-toolwindow", 1) | 窗口不顯示在任務(wù)欄 |
| 禁止調(diào)整 | resizable(0, 0) | 窗口大小固定 |
按鈕邏輯:
def OK():
root.destroy() # 銷毀彈窗
Meteors() # 啟動流星雨
def NO():
tk.messagebox.showwarning('?', '再給你一次機會!')
def closeWindow():
tk.messagebox.showwarning('?', '逃避是沒有用的哦')
流星形狀 —— 數(shù)學(xué)之美
每顆流星由兩段直線 + 一段圓弧組成,形成一個"水滴"或"彗星"形狀:
def star(self):
t.pensize(self.outline)
t.penup()
t.goto(self.x, self.y)
t.pendown()
t.color(self.color)
t.begin_fill()
t.fillcolor(self.color)
t.setheading(-30) # 初始朝向:右下 30°
t.right(self.t) # 偏轉(zhuǎn)隨機角度 t
t.forward(self.r) # 前進 r(流星長度)
t.left(self.t) # 回正
# 畫圓?。喊霃?= r * sin(t°),角度 = 180°
t.circle(self.r * math.sin(math.radians(self.t)), 180)
t.left(self.t)
t.forward(self.r) # 返回起點
t.end_fill()
幾何分析:
起點
\ 圓弧(180°)
\ /
* —— 頂點
/ \
/ \
/ \
終點 中點
整體形狀:"水滴"或"柳葉"
偏轉(zhuǎn)角 t 越大,流星越"胖"
長度 r 越大,流星越長
關(guān)鍵公式:
圓弧半徑=r×sin?(t°)
其中 t∈[1°,3°],r∈[50,100]
當 t 很小時,sin?(t°)≈t°×π/180,圓弧接近半圓,流星呈細長水滴狀。
流星運動 —— 循環(huán)重生
def move(self):
if self.y >= -500: # 還在畫布內(nèi)
self.y -= self.speed # 向下移動
self.x += 2 * self.speed # 向右移動(斜率 2:1)
else:
# 超出畫布,重置參數(shù),從上方重新出現(xiàn)
self.r = ra.randint(50, 100)
self.t = ra.randint(1, 3)
self.x = ra.randint(-2000, 1000)
self.y = 444
self.speed = ra.randint(5, 10)
self.color = ra.choice(colors)
運動軌跡:
屏幕坐標系(turtle):
y ↑
│
999 ├────────── 流星生成區(qū)
│ \ \ \
444 ├─────\────\────\───
│ \ \ \
│ \ \ \
│ \ \ \
-500├─────────\────\────\── 消失邊界
│ \ \ \
└────────────────────────→ x
-2000 1000
參數(shù)范圍:
| 參數(shù) | 范圍 | 作用 |
|---|---|---|
r | 50-100 | 流星長度 |
t | 1-3 | 偏轉(zhuǎn)角度(影響胖瘦) |
x | -2000 ~ 1000 | 初始水平位置 |
y | 444 ~ 999 | 初始垂直位置 |
speed | 5-10 | 下落速度 |
color | skyblue/white/cyan/aqua | 顏色 |
雙緩沖動畫 —— 消除閃爍
tu.tracer(0) # 關(guān)閉自動刷新 # ... 繪制所有流星 ... tu.update() # 手動刷新一次
原理: tracer(0) 關(guān)閉 turtle 的自動渲染,所有繪制操作先在內(nèi)存中完成,最后調(diào)用 update() 一次性顯示到屏幕,避免逐幀繪制導(dǎo)致的閃爍。
對比:
| 模式 | 代碼 | 效果 |
|---|---|---|
| 默認 | 無 tracer | 每步都刷新,嚴重閃爍 |
| 雙緩沖 | tracer(0) + update() | 批量刷新,流暢無閃爍 |
顏色主題切換
# 藍色主題(默認) colors = ['skyblue', 'white', 'cyan', 'aqua'] # 粉色主題(注釋掉的浪漫選項) # colors = ['pink', 'lightpink', 'deeppink']
只需注釋/取消注釋即可切換整體色調(diào)!
快速開始
步驟 1:直接運行
python 流星雨.py
無需安裝任何依賴,Python 內(nèi)置庫即可運行!
步驟 2:自定義表白文字
tk.Label(root, text='這里寫你的表白語', width=37, font=('宋體', 12))
步驟 3:調(diào)整流星數(shù)量
for i in range(100): # 默認 100 顆,改小更流暢,改大更壯觀
Stars.append(Star())
while True:
for i in range(100): # 與上面保持一致
Stars[i].move()
Stars[i].star()
步驟 4:調(diào)整畫布邊界
# 流星重生邊界 if self.y >= -500: # 下邊界,改小流星飛得更遠 # 初始位置范圍 self.x = ra.randint(-2000, 1000) # 水平范圍 self.y = ra.randint(444, 999) # 垂直范圍(生成高度)
自定義改造指南
改造 1:添加背景音樂
import pygame
pygame.mixer.init()
pygame.mixer.music.load("romantic.mp3")
pygame.mixer.music.play(-1) # 循環(huán)播放
改造 2:流星拖尾效果
def move(self):
# 保存歷史位置
self.trail.append((self.x, self.y))
if len(self.trail) > 5:
self.trail.pop(0)
# 繪制拖尾
for i, (tx, ty) in enumerate(self.trail):
alpha = i / len(self.trail)
t.pensize(self.outline * alpha)
t.goto(tx, ty)
改造 3:添加星星背景
def draw_background():
t.penup()
for _ in range(200):
x = ra.randint(-1000, 1000)
y = ra.randint(-500, 500)
t.goto(x, y)
t.dot(2, 'white') # 畫小星星
改造 4:表白成功后的文字
def OK():
root.destroy()
# 顯示成功文字
success = tk.Tk()
tk.Label(success, text='?? 余生請多指教 ??',
font=('華文行楷', 24), fg='red').pack()
success.after(2000, Meteors) # 2秒后進入流星雨
success.mainloop()
改造 5:多行表白語
messages = [
'遇見你,是我最美的意外',
'愿余生與你,星河滾燙',
'做我女朋友好嗎?'
]
for i, msg in enumerate(messages):
tk.Label(root, text=msg, font=('宋體', 12)).place(x=0, y=10 + i*20)
完整源碼
import turtle as tu
import random as ra
import tkinter as tk
import math
def Meteors():
tu.setup(1.0, 1.0)
tu.screensize(1.0, 1.0)
tu.bgcolor('black')
tu.title("流星雨")
t = tu.Pen()
t.hideturtle()
colors = ['skyblue', 'white', 'cyan', 'aqua']
class Star():
def __init__(self):
self.r = ra.randint(50,100)
self.t = ra.randint(1,3)
self.x = ra.randint(-2000,1000)
self.y = ra.randint(444, 999)
self.speed = ra.randint(5,10)
self.color = ra.choice(colors)
self.outline = 1
def star(self):
t.pensize(self.outline)
t.penup()
t.goto(self.x,self.y)
t.pendown()
t.color(self.color)
t.begin_fill()
t.fillcolor(self.color)
t.setheading(-30)
t.right(self.t)
t.forward(self.r)
t.left(self.t)
t.circle(self.r*math.sin(math.radians(self.t)),180)
t.left(self.t)
t.forward(self.r)
t.end_fill()
def move(self):
if self.y >= -500:
self.y -= self.speed
self.x += 2*self.speed
else:
self.r = ra.randint(50,100)
self.t = ra.randint(1,3)
self.x = ra.randint(-2000,1000)
self.y = 444
self.speed = ra.randint(5,10)
self.color = ra.choice(colors)
self.outline = 1
Stars = []
for i in range(100):
Stars.append(Star())
while True:
tu.tracer(0)
t.clear()
for i in range(100):
Stars[i].move()
Stars[i].star()
tu.update()
tu.mainloop()
def love():
root = tk.Tk()
root.title('?')
root.resizable(0, 0)
root.wm_attributes("-toolwindow", 1)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
widths = 300
heights = 100
x = (screenwidth - widths) / 2
y = (screenheight - heights) / 2
root.geometry('%dx%d+%d+%d' % (widths, heights, x, y))
tk.Label(root, text='親愛的,做我女朋友好嗎?', width=37, font=('宋體', 12)).place(x=0, y=10)
def OK():
root.destroy()
Meteors()
def NO():
tk.messagebox.showwarning('?', '再給你一次機會!')
def closeWindow():
tk.messagebox.showwarning('?', '逃避是沒有用的哦')
tk.Button(root, text='好哦', width=5, height=1, command=OK).place(x=80, y=50)
tk.Button(root, text='不要', width=5, height=1, command=NO).place(x=160, y=50)
root.protocol('WM_DELETE_WINDOW', closeWindow)
root.mainloop()
if __name__ == "__main__":
love()
總結(jié)
本項目展示了 Python 標準庫的強大表現(xiàn)力:
- ? tkinter:零依賴 GUI,彈窗交互
- ? turtle:簡單繪圖,適合教學(xué)與演示
- ? 對象封裝:
Star類管理每顆流星狀態(tài) - ? 雙緩沖:
tracer(0)+update()流暢動畫 - ? 事件綁定:攔截關(guān)閉按鈕,"強制"表白
以上就是Python turtle打造一個浪漫流星雨表白程序的詳細內(nèi)容,更多關(guān)于Python turtle流星雨表白程序的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python配置文件管理之ini和yaml文件讀取的實現(xiàn)
本文主要介紹了Python配置文件管理之ini和yaml文件讀取,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2023-02-02
Python實現(xiàn)Word轉(zhuǎn)PDF全攻略(從入門到實戰(zhàn))
在數(shù)字化辦公場景中,Word文檔的跨平臺兼容性始終是個難題,而PDF格式憑借"所見即所得"的特性,已成為文檔分發(fā)和歸檔的標準格式,下面小編就來和大家講講如何使用Python實現(xiàn)Word轉(zhuǎn)PDF吧2025-08-08
Python2與Python3的區(qū)別實例總結(jié)
這篇文章主要介紹了Python2與Python3的區(qū)別,結(jié)合實例形式總結(jié)分析了Python2與Python3打印輸出、編碼、數(shù)值運算、異常處理等使用區(qū)別,需要的朋友可以參考下2019-04-04

