import tkinter as tk
import random
import math
class Firework:
def __init__(self, canvas, color):
self.canvas = canvas
self.colors = ["#ff0000", "#ffff00", "#00ff00", "#00ffff", "#ff00ff"]
self.particles = []
self.create_firework(color)
def create_firework(self, color):
x = random.randint(100, 700)
y = random.randint(100, 500)
for _ in range(50):
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(1, 5)
dx = math.cos(angle) * speed
dy = math.sin(angle) * speed
particle = self.canvas.create_oval(
x, y, x + 5, y + 5,
fill=random.choice(self.colors),
outline=random.choice(self.colors)
)
self.particles.append((particle, dx, dy))
def update(self):
to_remove = []
for i, (particle, dx, dy) in enumerate(self.particles):
self.canvas.move(particle, dx, dy)
x0, y0, x1, y1 = self.canvas.coords(particle)
if x0 < 0 or x1 > 800 or y0 < 0 or y1 > 600:
to_remove.append(i)
for index in reversed(to_remove):
particle, _, _ = self.particles.pop(index)
self.canvas.delete(particle)
class App:
def __init__(self, root):
self.root = root
self.root.title("蛇年大吉 - 烟花特效")
self.canvas = tk.Canvas(root, width=800, height=600, bg='black')
self.canvas.pack()
# 添加祝福文字
self.canvas.create_text(400, 300,
text="蛇年大吉",
font=("华文行楷", 72, "bold"),
fill="#FFD700",
tags="text")
self.fireworks = []
self.animate()
def animate(self):
if random.random() < 0.1:
color = "#{:02x}{:02x}{:02x}".format(
random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255)
)
self.fireworks.append(Firework(self.canvas, color))
for firework in self.fireworks[:]:
firework.update()
if not firework.particles:
self.fireworks.remove(firework)
self.root.after(30, self.animate)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.mainloop()
效果展示: