idle和tkinter的烟花代码
时间: 2023-11-20 10:56:31 浏览: 66
以下是使用Python的IDLE和Tkinter模块编写的烟花代码:
```python
import tkinter as tk
import random
class Particle:
def __init__(self, canvas, x, y, size, color):
self.canvas = canvas
self.id = canvas.create_oval(x, y, x+size, y+size, fill=color)
self.vx = random.uniform(-1, 1)
self.vy = random.uniform(-1, 1)
self.size = size
self.color = color
self.age = 0
self.lifespan = random.randint(10, 50)
def move(self):
self.canvas.move(self.id, self.vx, self.vy)
self.vx *= 0.99
self.vy *= 0.99
self.age += 1
def expand(self):
return self.age <= 1.2
def alive(self):
return self.age <= self.lifespan
class Firework:
def __init__(self, canvas, x, y):
self.canvas = canvas
self.particles = []
self.x = x
self.y = y
self.color = "#%06x" % random.randint(0, 0xFFFFFF)
for i in range(50):
size = random.randint(2, 6)
p = Particle(canvas, x, y, size, self.color)
self.particles.append(p)
def move(self):
for p in self.particles:
p.move()
def expand(self):
return all([p.expand() for p in self.particles])
def alive(self):
return any([p.alive() for p in self.particles])
def launch_firework(canvas):
x = random.randint(50, 550)
y = random.randint(50, 250)
f = Firework(canvas, x, y)
fireworks.append(f)
def draw(canvas):
global fireworks
for f in fireworks:
if f.alive():
if f.expand():
f.move()
else:
canvas.delete(f)
fireworks.remove(f)
else:
canvas.delete(f)
fireworks.remove(f)
canvas.after(10, draw, canvas)
fireworks = []
root = tk.Tk()
root.title("Fireworks")
canvas = tk.Canvas(root, width=600, height=300)
canvas.pack()
button = tk.Button(root, text="Launch Firework", command=lambda: launch_firework(canvas))
button.pack()
canvas.after(10, draw, canvas)
root.mainloop()
```
这个程序使用Tkinter模块创建了一个窗口,其中包含一个画布和一个按钮。当用户点击按钮时,程序会在画布上发射一个烟花。每个烟花由多个粒子组成,每个粒子都有自己的位置、速度、大小和颜色。程序使用一个循环来更新每个粒子的位置,并在粒子的寿命结束后将其从画布上删除。