Python 实现屏幕爱心弹窗效果
这是一个用 Python 编写的趣味脚本,利用 tkinter 库在屏幕上生成动态爱心弹窗。程序会先在屏幕中央形成爱心图案,随后在全屏随机显示带有温馨话语的彩色窗口,最后自动关闭。
环境要求
运行此脚本需要以下基础环境:
- 操作系统:Windows 10/11、macOS 10.14+ 或 Linux(需图形界面)
- Python 版本:Python 3.x
- 依赖库:
tkinter(通常随 Python 安装,无需额外 pip install) - 硬件:建议至少 2GB 可用内存,支持任意分辨率显示器
检查 Python 安装
打开命令行或终端,输入以下命令确认版本:
python --version
若显示 Python 3.x 版本号,说明环境已就绪。
核心代码
将以下代码保存为 love.py。注意导入语句已分行整理,确保缩进正确。
import random
import tkinter as tk
import threading
import math
import time
# 温馨提示语列表
tips = [
"我想你了", "别熬夜哦", "要开心呀", "我爱你",
"早点休息", "记得吃饭", "多喝热水", "你最棒啦",
"晚安好梦", "I LOVE YOU", "照顾好自己", "想见到你",
"一直在等你", "别太累了"
]
# 自动获取屏幕分辨率
try:
root_temp = tk.Tk()
SCREEN_W = root_temp.winfo_screenwidth()
SCREEN_H = root_temp.winfo_screenheight()
root_temp.destroy()
except:
SCREEN_W = 1920
SCREEN_H = 1080
# 弹窗尺寸
WINDOW_W = 120
WINDOW_H = 60
# 存储所有窗口引用
all_windows = []
def ():
points = []
t (num_points):
t_rad = t / num_points * * math.pi
x = * (math.sin(t_rad) ** )
y = * math.cos(t_rad) - * math.cos( * t_rad) - * math.cos( * t_rad) - math.cos( * t_rad)
screen_x = SCREEN_W // + x *
screen_y = SCREEN_H // - y *
screen_x = (WINDOW_W // , (screen_x, SCREEN_W - WINDOW_W // ))
screen_y = (WINDOW_H // , (screen_y, SCREEN_H - WINDOW_H // ))
points.append(((screen_x - WINDOW_W // ), (screen_y - WINDOW_H // )))
points
():
root = tk.Tk()
root.overrideredirect()
root.attributes(, )
r = random.randint(, )
g = random.randint(, )
b = random.randint(, )
root.configure(bg=)
tip = random.choice(tips)
label = tk.Label(root, text=tip, font=(, , ), bg=, fg=, wraplength=WINDOW_W-)
label.pack(fill=tk.BOTH, expand=, padx=, pady=)
root.geometry()
all_windows.append(root)
root.after(, root.destroy)
root.mainloop()
():
root = tk.Tk()
root.overrideredirect()
root.attributes(, )
r = random.randint(, )
g = random.randint(, )
b = random.randint(, )
root.configure(bg=)
tip = random.choice(tips)
label = tk.Label(root, text=tip, font=(, , ), bg=, fg=, wraplength=WINDOW_W-)
label.pack(fill=tk.BOTH, expand=, padx=, pady=)
x = random.randint(, SCREEN_W - WINDOW_W)
y = random.randint(, SCREEN_H - WINDOW_H)
root.geometry()
all_windows.append(root)
root.after(, root.destroy)
root.mainloop()
():
cols = (SCREEN_W // WINDOW_W) +
rows = (SCREEN_H // WINDOW_H) +
total_windows = cols * rows
()
threads = []
i (total_windows):
t = threading.Thread(target=create_random_window)
threads.append(t)
t.start()
i % == :
time.sleep()
():
heart_points = generate_heart_points()
()
threads = []
i, (x, y) (heart_points):
t = threading.Thread(target=show_heart_window, args=(x, y))
threads.append(t)
t.start()
time.sleep()
time.sleep()
center_x = SCREEN_W // - WINDOW_W //
center_y = SCREEN_H // - WINDOW_H //
()
fullscreen_thread = threading.Thread(target=create_fullscreen_windows)
fullscreen_thread.start()
__name__ == :
animation_thread = threading.Thread(target=heart_animation)
animation_thread.start()
:
:
time.sleep()
KeyboardInterrupt:
()
window all_windows:
:
window.destroy()
:


