绿色圃中小学教育网

python画长方形并涂色代码

[原创]
导读 Python是一种流行的编程语言,可以通过它来画出各种形状并。绿色圃中小学教育网百科专栏,提供全方位全领域的生活知识

Python是一种流行的编程语言,可以通过它来画出各种形状并涂上不同颜色。本文将介绍如何使用Python来画长方形并给它涂上颜色。

首先,我们需要导入Python中的绘图库`turtle`。这个库可以让我们在屏幕上绘制各种形状。

```python

import turtle

```

接下来,我们需要定义一个函数来画长方形。这个函数需要传入长方形的宽度和高度。

```python

def draw_rectangle(width, height):

turtle.penup()

turtle.goto(-width/2, height/2)

turtle.pendown()

turtle.begin_fill()

turtle.color('red')

for i in range(2):

turtle.forward(width)

turtle.right(90)

turtle.forward(height)

turtle.right(90)

turtle.end_fill()

```

上述代码中,我们使用`penup()`和`pendown()`函数来控制画笔的位置。然后使用`goto()`函数将画笔移动到长方形的左上角。接着使用`begin_fill()`函数开始填充颜色,使用`color()`函数设置颜色为红色。接下来使用循环语句画出长方形的四条边,最后使用`end_fill()`函数结束填充。

最后,我们可以调用`draw_rectangle()`函数来画出长方形。

```python

draw_rectangle(200, 100)

```

上述代码中,我们传入长方形的宽度为200,高度为100,画出一个200x100的红色长方形。

完整代码如下:

```python

import turtle

def draw_rectangle(width, height):

turtle.penup()

turtle.goto(-width/2, height/2)

turtle.pendown()

turtle.begin_fill()

turtle.color('red')

for i in range(2):

turtle.forward(width)

turtle.right(90)

turtle.forward(height)

turtle.right(90)

turtle.end_fill()

draw_rectangle(200, 100)

turtle.done()

```

运行以上代码,你将看到在屏幕上画出一个红色的长方形。