python炫酷浪漫烟花
时间: 2023-12-30 18:04:07 浏览: 194
以下是一个用Python实现炫酷浪漫烟花的例子:
```python
import tkinter as tk
import random
# 创建画布
canvas_width = 800
canvas_height = 600
canvas = tk.Canvas(width=canvas_width, height=canvas_height)
canvas.pack()
# 定义烟花粒子类
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = random.choice(['red', 'orange', 'yellow', 'green', 'blue', 'purple'])
self.size = random.randint(1, 5)
self.x_velocity = random.uniform(-1, 1)
self.y_velocity = random.uniform(-1, 1)
self.lifespan = random.randint(50, 100)
def update(self):
self.x += self.x_velocity
self.y += self.y_velocity
self.lifespan -= 1
def draw(self):
canvas.create_oval(self.x - self.size, self.y - self.size, self.x + self.size, self.y + self.size, fill=self.color)
# 创建烟花函数
def create_firework(event):
x = event.x
y = event.y
for _ in range(50):
particle = Particle(x, y)
particles.append(particle)
# 更新和绘制粒子
def update_particles():
for particle in particles:
particle.update()
particle.draw()
particles[:] = [particle for particle in particles if particle.lifespan > 0]
canvas.after(10, update_particles)
# 绑定鼠标点击事件
canvas.bind('<Button-1>', create_firework)
# 存储粒子的列表
particles = []
# 开始更新和绘制粒子
update_particles()
# 运行主循环
canvas.mainloop()
```
阅读全文