Python代码画星空与烟花
时间: 2024-01-10 16:04:39 浏览: 133
画星空:
```python
import turtle
import random
# 设置画布大小和背景颜色
turtle.setup(800, 600)
turtle.bgcolor("black")
# 设置画笔属性
turtle.pensize(3)
turtle.color("white")
# 画星星
for i in range(50):
x = random.randint(-400, 400)
y = random.randint(-300, 300)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.dot()
# 隐藏画笔
turtle.hideturtle()
# 等待用户关闭窗口
turtle.done()
```
画烟花:
```python
import turtle
import random
# 设置画布大小和背景颜色
turtle.setup(800, 600)
turtle.bgcolor("black")
# 设置画笔属性
turtle.pensize(3)
turtle.color("white")
# 定义画烟花的函数
def draw_firework(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.dot()
for i in range(25):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color(random.choice(["red", "orange", "yellow", "white"]))
turtle.setheading(random.randint(0, 360))
turtle.forward(random.randint(50, 150))
turtle.dot()
# 注册鼠标点击事件
turtle.onscreenclick(draw_firework)
# 隐藏画笔
turtle.hideturtle()
# 等待用户关闭窗口
turtle.done()
```
运行代码后,可以点击画布上任意位置,就会发射一个烟花。
阅读全文