写一个用turtle库画漫天星空的python代码
时间: 2023-12-17 07:47:13 浏览: 39
以下是一个用turtle库画漫天星空的Python代码:
```python
import turtle
import random
# 创建画布和画笔
canvas = turtle.Screen()
canvas.bgcolor("black")
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.ht()
# 循环画星星
for i in range(200):
# 随机生成星星位置
x = random.randint(-400, 400)
y = random.randint(-400, 400)
# 移动画笔到星星位置
pen.penup()
pen.goto(x, y)
pen.pendown()
# 随机生成星星大小
size = random.randint(1, 4)
# 画星星
for j in range(5):
pen.fd(size)
pen.rt(144)
# 关闭画布
canvas.exitonclick()
```
运行代码后,会出现一个黑色背景的画布,上面画着很多大小不一、位置随机的白色星星,就像漫天繁星一样美丽。
相关问题
用python代码turtle库画一个党徽
好的,以下是使用Python的turtle库画党徽的代码:
```python
import turtle
# 设置画布大小和背景色
turtle.setup(800, 600)
turtle.bgcolor("#DE2910")
# 画黄色的五角星
turtle.color("#FFDE00")
turtle.begin_fill()
for i in range(5):
turtle.forward(200)
turtle.right(144)
turtle.end_fill()
# 画红色的大圆
turtle.penup()
turtle.goto(0, -80)
turtle.pendown()
turtle.color("#FF0000")
turtle.begin_fill()
turtle.circle(80)
turtle.end_fill()
# 画黄色的小圆
turtle.penup()
turtle.goto(0, -60)
turtle.pendown()
turtle.color("#FFDE00")
turtle.begin_fill()
turtle.circle(60)
turtle.end_fill()
# 隐藏画笔
turtle.hideturtle()
# 保持窗口不关闭
turtle.done()
```
运行以上代码,即可在窗口中看到画好的党徽。效果如下:
![党徽](https://img-blog.csdnimg.cn/20210622180436703.png)
利用turtle库画五彩的Python字母 Python
在Python中,`turtle`库是一个非常有趣且直观的图形库,特别适合教学和创建简单的动画效果,包括绘制几何图形。要使用turtle库画出五彩的字母,你可以结合循环、颜色变化和turtle的基本形状函数来实现。以下是一个简单的例子,展示如何用turtle绘制彩色的'W'字母:
```python
import turtle
import random
# 设置颜色列表
colors = ['red', 'blue', 'green', 'yellow', 'purple']
# 定义绘制字母的函数
def draw_letter(letter, color):
t = turtle.Turtle()
t.color(color)
for segment in letter: # 假设我们有一个包含字母路径的列表
if segment == 'up':
t.penup()
elif segment == 'down':
t.pendown()
else: # 这里假设segment是前进一段距离
t.forward(20)
t.left(90)
# 创建一个五彩的字母 'W'
draw_letter(['forward', 'right', 'down', 'forward', 'right', 'forward', 'up'], random.choice(colors))
turtle.done()
# 你可以为每个字母的每个部分选择随机颜色,这里只是举个例子
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)