Turtle python как закрасить

Python turtle Colors – How to Color and Fill Shapes with turtle Module

The Python turtle module provides us with many functions which allow us to add color to the shapes we draw.

You can use any valid Tk color name with turtle module, as well as RGB colors. Some colors include:

colors = ['yellow', 'cyan', 'red', 'light blue', 'pink', 'blue', 'purple', 'green', 'orange']

Below is a brief summary of how to use turtle colors in Python.

To change the pen color, we can use the pencolor() function.

import turtle t = turtle.Turtle() t.pencolor("green")

For changing the fill color, we can use the fillcolor() function.

import turtle t = turtle.Turtle() t.fillcolor("blue")

To begin and end filling a shape, we use the begin_fill() and end_fill() functions.

import turtle t = turtle.Turtle() t.fillcolor("blue") t.begin_fill() t.circle(50) t.end_fill()

If you are looking to change the background color of the turtle screen, you can use the screensize() function.

import turtle turtle.screensize(bg="red")

The turtle module in Python allows us to create graphics easily in our Python code.

We can use the turtle module to make all sorts of designs with Python. With those designs, the turtle module gives a number of ways to color our designs.

We can add color to the lines, as well as fill the shapes we create with color.

The main function you can use to change the color of a line is with the turtle pencolor() function.

Below is an example and the output of how to change the color of a line using pencolor() in Python.

import turtle t = turtle.Turtle() t.pencolor("green") t.circle(50)

turtle color green circle

To fill a shape, there are a few steps to take. We use the fillcolor() function to define the fill color of our shape, and then use the begin_fill() and end_fill() functions to define when to begin and end filling shapes with the fill color.

Below is an example and the output of how to fill a circle with the color ‘blue’ using fillcolor(), begin_fill() and end_fill() in Python.

import turtle t = turtle.Turtle() t.fillcolor("blue") t.begin_fill() t.circle(50) t.end_fill()

turtle fill color blue circle

Python turtle Color List – Which Colors Can You Use?

With the turtle module, we can use a number of different colors. The colors you can use with the turtle module are all of the many symbolic color names that Tk recognizes.

Читайте также:  Process pool executor python

The list is hundreds of colors long, but below are a handful of common colors you can use with turtle.

colors = ['yellow', 'cyan', 'red', 'light blue', 'pink', 'blue', 'purple', 'green', 'brown', 'orange']

Using RGB Colors with Python turtle Module

In addition to the list of turtle colors, you can use RGB to define your own colors. To use RGB colors with turtle, you have to change the color mode to ‘255’ with the colormode() function.

After changing the color mode of the turtle to RGB mode, you can pass three integer values between 0 and 255 representing the red, green and blue contributions to a RGB color.

Below are a few examples of how to use RGB colors with turtle in Python.

import turtle turtle.colormode(255) t = turtle.Turtle() t.pencolor(200,100,150) t.circle(50)

turtle rgb colors circle

Changing the Turtle Pen Color in Python

With the turtle colors in Python, we can change the pen color to change the colors of the lines in our designs.

To change the pen color, you can use the pencolor() function. Depending on the color mode, you can pass any valid color to pencolor().

Below is an example of drawing a rectangle which has a green outline in Python.

import turtle t = turtle.Turtle() t.pencolor("green") def draw_rectangle(length, height): for i in range(0,4): if i % 2 == 0: t.forward(length) t.right(90) else: t.forward(height) t.right(90) draw_rectangle(200, 100)

turtle green rectangle

Changing the Turtle Fill Color in Python

With the turtle colors, you can easily fill shapes with color.

To fill a shape, there are a few steps to take. We use the fillcolor() function to define the fill color of our shape, and then use the begin_fill() and end_fill() functions to define when to begin and end filling shapes with the fill color.

Just like the pencolor() function, the fillcolor() function takes any valid color given a color mode.

Let’s take the example from above and fill our rectangle with the color ‘light blue’ using fillcolor(), begin_fill() and end_fill() in Python.

import turtle t = turtle.Turtle() t.fillcolor("light blue") t.pencolor("green") t.begin_fill() def draw_rectangle(length, height): for i in range(0,4): if i % 2 == 0: t.forward(length) t.right(90) else: t.forward(height) t.right(90) draw_rectangle(200, 100) t.end_fill()

turtle rectangle light blue fill color

Generating a Random Color Turtle with Python turtle Module

When creating graphics, sometimes it’s cool to be able to generate random colors to make random colored shapes or designs.

We can generate random colors using RGB colors. To use RGB colors, we change the color mode to RGB mode (‘255’), and then we use the randint() function from the random module to generate random numbers in the range 0 to 255.

Below is an example of how to use Python to get a random color to draw a triangle and then fill it with turtle.

import turtle from random import randint turtle.colormode(255) t = turtle.Turtle() t.pencolor(randint(0,255),randint(0,255),randint(0,255)) t.fillcolor(randint(0,255),randint(0,255),randint(0,255)) t.begin_fill() def draw_triangle(side_length): for i in range(0,3): t.forward(side_length) t.right(120) draw_triangle(100) t.end_fill()

random colors triangle turtle

As you can see, we randomly got a dark color for the pen color, and an orange color for the fill color.

Читайте также:  Css height all screen

Changing Color When Drawing Different Shapes with the Python turtle Module

When working with shapes, sometimes we want to make different sides of the shapes different colors.

We can generate random color turtles in Python easily. Since the turtle module works in steps, we just need to tell our turtle which color it should use at each step.

So for example, if we want to draw a square with 4 different color sides, before drawing each side, we just need to tell our turtle which color to use. We can use our random color generator from the last example to generate random colors for our square.

Below is an example of how to draw a square with 4 different color sides in Python with turtle.

import turtle from random import randint turtle.colormode(255) t = turtle.Turtle() def draw_square(length): for i in range(0,4): t.pencolor(randint(0,255),randint(0,255),randint(0,255)) t.forward(length) t.right(90) draw_square(100)

turtle square different color sides

Another application of changing colors when drawing a shape is creating a spiral which changes color as it gets bigger and bigger.

Below is an example of a spiral that changes color as it gets bigger in Python.

import turtle from random import randint turtle.colormode(255) t = turtle.Turtle() def draw_spiral(starting_radius, loops): for i in range(0, loops): t.pencolor(randint(0,255),randint(0,255),randint(0,255)) t.circle(starting_radius + i, 60) draw_spiral(10, 50)

turtle spiral random colors

Changing the Background Color of the turtle Screen in Python

One final application of using turtle colors is to change the background color of the turtle screen. We change the color of the turtle screen with the screensize() function.

To change the background color of the turtle screen, you can use the ‘bg’ argument and pass any of the valid turtle colors from the turtle color list.

Below is an example of how to change the turtle screen background color in Python.

import turtle turtle.screensize(bg="red")

turtle background color red

Hopefully this article has been helpful for you to learn how to use colors with the turtle module in Python.

  • 1. Convert Integer to Bytes in Python
  • 2. How to Convert pandas Column dtype from Object to Category
  • 3. Using Python to Search File for String
  • 4. Using Python to Remove Last Character from String
  • 5. math.degrees() Python – How to Convert Radians to Degrees in Python
  • 6. Using GroupBy() to Group Pandas DataFrame by Multiple Columns
  • 7. Drop Last Row of pandas DataFrame
  • 8. Check if Line is Empty in Python
  • 9. Using Python to Get Queue Size
  • 10. How to Read Pickle File from AWS S3 Bucket Using Python
Читайте также:  Php if and or combined

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Команды для рисования Черепашкой

Перемещать черепашку мы уже умеем. Теперь научимся работать с пером. Перо – это инструмент с помощью которого Черепашка рисует линии.
Команда turtle.penup() подымает перо. После чего, Черепашка не оставляет на холсте след. Чтобы начать снова рисовать необходимо опустить перо командой turtle.pendown(). По умолчанию у Черепашки перо всегда опущено. Команды penup() и pendown() применяются без аргументов в скобках.

#Подымаем перо turtle.penup()
#Опускаем перо turtle.pendown()

Сокращенные версии команды: turtle.up() или turtle.pu() чтобы поднять перо и turtle.down() или turtle.pd() чтобы опустить.
Еще одно свойство пера – это его толщина. То, насколько толстым будет след оставляемый Черепашкой. Устанавливается он командой turtle.pensize() или turtle.width(), где в скобках указывается число, толщина в пикселях линии, которую рисует Черепашка.

#Рисуем линию толщиной в пять пикселей turtle.pensize(5)

По умолчанию Черепашка рисует линию черным цветом. Но с помощью команды turtle.pencolor() мы можем его изменить.
В качестве аргументов мы можем записать название цвета, на английском языке, которым Черепашка должна будет рисовать линии. Например red, green или blue. Передаваемые названия должны быть обязательно взяты в кавычки или апострофы.

#Рисуем линии красным цветом turtle.pencolor('red')

Цвет также можно задать используя палитру RGB, записав три числа от 0 до 255 через запятую.

#Рисуем линии зеленым цветом используя RGB палитру turtle.pencolor(0,255,0)

Либо задав цвет в виде шестнадцатеричного числа, так же взяв его в кавычки или апострофы.

#Рисуем линии синим цветом используя шестнадцатеричную запись turtle.pencolor('#0000ff')

Черепашка может закрашивать замкнутые области. Для начала необходимо установить цвет заливки используя команду turtle.fillcolor(). В качестве аргументов указываем цвет, как и в цветет линии.
Для того, чтобы указать начало заливки задаем команду turtle.begin_fill(), а чтобы закончить turtle.end_fill().

#Указываем цвет заливки turtle.fillcolor('#0000ff') turtle.begin_fill() #Тут записываем команды движения Черепашки turtle.end_fill()

Для заливки необязательно Черепашкой рисовать замкнутую область. В этом случае между местом откуда мы начали заливку и где ее закончили будет проведена граница, по которой и пройдет заливка фигуры.
Менять цвет линии и заливки можно так-же командой turtle.color(). Этой команду можно передать как один аргумент, так и два, записав их через запятую. Первый аргумент устанавливает цвет линии, а второй цвет заливки.

#Первый аргумент изменяет цвет линии, второй цвет заливки turtle.color('#0000ff', 'red')

Источник

Оцените статью