Простое рисование с помощью черепашки¶
У неё есть функции в стиле turtle.forward(. ) и turtle.left(. ) , с помощью которых черепашка может двигаться.
Перед тем как начать работу с черепашкой, необходимо импортировать соответствующий модуль. Мы рекомендуем экспериментировать с ней в интерактивной оболочке (для начала), т.к. при использовании файлов придётся заниматься дополнительной утомительной работой. Перейди в терминал и введи:

Not seeing anything on Mac OS? Try issuing a command like turtle.forward(0) and looking if a new window opened behind your command line.
Используешь Ubuntu и получаешь сообщение об ошибке “No module named _tkinter”? Установи отсутствующий необходимый пакет: sudo apt-get install python3-tk
While it might be tempting to just copy and paste what’s written on this page into your terminal, we encourage you to type out each command. Typing gets the syntax under your fingers (building that muscle memory!) and can even help avoid strange syntax errors.


Функция turtle.forward(. ) заставляет черепашку двигаться вперёд на указанное расстояние. turtle.left(. ) приказывает черепашке повернуться влево на указанную градусную меру угла. А turtle.backward(. ) и turtle.right(. ) действуют анлогично — первая заставляет черепашку двигаться назад, а вторая — поворачиваться вправо.
Если ты хочешь начать заново, введи turtle.reset() , чтобы стереть рисунок. Мы рассмотрим turtle.reset() подробнее немного позже.
Стандартная “черепашка” – всего лишь треугольник. Это не интересно! Придадим ей нормальный вид командой turtle.shape() :
Так намного лучше!
If you put the commands into a file, you might have recognized that the turtle window vanishes after the turtle finished its movement. (That is because Python exits when your turtle has finished moving. Since the turtle window belongs to Python, it terminates as well.) To prevent that, just put turtle.exitonclick() at the bottom of your file. Now the window stays open until you click on it:
Python — язык программирования, в котором крайне важны отступы в коде. Подробности мы узнаем позже, в главах про функции, но сейчас тебе просто необходимо запомнить, что лишний пробел или символ табуляции перед строкой может вызвать ошибку.
Рисуем квадрат¶
You’re not always expected to know the anwer immediately. Learn by trial and error! Experiment, see what python does when you tell it different things, what gives beautiful (although sometimes unexpected) results and what gives errors. If you want to keep playing with something you learned that creates interesting results, that’s OK too. Don’t hesitate to try and fail and learn from it!
Упражнение¶
Нарисуй квадрат, как на рисунке ниже:

Для квадрата тебе понадобится прямоугольный, т.е. 90-градусный, угол.
Решение¶
Notice how the turtle starts and finishes in the same place and facing the same direction, before and after drawing the square. This is a useful convention to follow, it makes it easier to draw multiple shapes later on.
Рисуем геометрические фигуры в Python с помощью Pillow

Модуль ImageDraw из библиотеки обработки изображений Pillow (PIL) предоставляет методы для рисования круга, квадрата и прямой линии в Python.
Содержание статьи
Создание объекта Draw в Python
Используя объекта Image мы создадим фоновое изображение на которой мы будем рисовать наши фигуры при помощи объекта Draw . Не забудьте импортировать модуль Image и ImageDraw в начале кода.
Здесь создается пустое изображение с размером 500 на 300 пикселей и с тёмно желтым фоном.

Рисуем фигуры в Pillow: ellipse, rectangle и line
Вызываем методы рисования из объекта Draw для рисования фигур на нашем желтом фоне.
Рисуем эллипс, прямоугольник и прямую линию в качестве примера.

Справочник по параметрам методов рисования
Даже если, способы рисования отличаются в зависимости от используемого метода, следующие параметры являются общими для всех.
Область рисования — xy
Параметр xy указывает прямоугольную область для рисования новой фигуры.
Уточняется один из следующих форматов:
- (((Верхняя левая x координата, Верхняя левая y координата), (нижняя правая x координата, нижняя правая y координата)) ;
- (Верхняя левая x координата, Верхняя левая y координата, нижняя правая x координата, нижняя правая y координата) .
В методах line() , polygon() и point() используются многочисленные координаты вместо двух точек, представляющих прямоугольную область.
- (x1, y1, x2, y2, x3, y3. ) ;
- ((x1, y1), (x2, y2), (x3, y3). ) .
Метод line() рисует прямую линию, которая связывает каждую точку, polygon() рисует многоугольник, а метод point() рисует точку в 1 пиксель для каждой указанной точки.
Параметр fill — заполняем фигуру определенным цветом
Параметр fill указывает какой цвет будет использован для заполнения нашей геометрической формы.
Спецификация формата цвета отличается в зависимости от указанного режима изображения (объект Image ):
- RGB : Указывает значение цвета в форме (R, G, B) ;
- L (Черно-белое): Указывает значение (0-255) как целое число).
Значение по умолчанию None (не заполнено).
Есть три способа указать цвет, возьмем красный цвет, его можно записать так:
- текстовый формат: red;
- CSS формат (Шестнадцатеричный): #FF0000
- RGB: (255, 0, 0)
Стоит учесть тот факт, что текстовый формат не имеет все цвета, кол-во доступных цветов ограничено в коде самой библиотеки. Вот весь список: https://github.com/python-pillow/Pillow/blob/8.1.0/src/PIL/ImageColor.py#L148
Лучше всего использовать шестнадцатеричный формат #FFFFFF (белый).
Параметр outline — цвет границ
Параметр outline указывает на цвет границы фигуры.
Спецификация формата цвета такая же, как и у параметра fill которого мы обсуждали выше. Значение по умолчанию равно None (без границ).
Параметр width — размер границ
Вне зависимости от рисуемой фигуры, вы можете указать размер в пикселях для границы фигуры.
Рисование эллипса и прямоугольника в Python
- Эллипс (Круг): ellipse(xy, fill, outline) ;
- Прямоугольник (Квадрат): rectangle(xy, fill, outline) .
Метод ellipse() рисует эллипс, область рисования указывается в параметр xy . Если мы зададим четыре координата которые будут соответствовать квадрату, то у нас получится ровный круг.
Python Turtle Square – Helpful Guide
In this Python tutorial, we will learn How to create Square in Python Turtle and we will also cover different examples related to Turtle square. And we will cover these topics.
- Python turtle square function
- Python turtle square loop
- Python turtle square spiral
- Python turtle square size
- Python turtle square root
- Python turtle square inside a square
- Python turtle square example
- Python turtle fill square with color
- Python turtle draw multiple squares
- Python turtle repeating square
Table of Contents
Python turtle square function
In this section, we will learn about the Turtle Square function in Python turtle.
In this, we use a built-in module in python (turtle). It uses to draw on the screen using a turtle (pen). To move turtle here are some functions that we use to give shapes forward() and backward().
CODE:
In the following code, we imported the turtle module in python, and with help of the forward() and left() functions, we generated a shape of a square.
- ws.forward(100) is forwarding turtle by 5 units
- ws.left(90) turn turtle by 90 degree.
Output:
In the following output, we have made a shape of a square with help of forward() and left() functions.
Python turtle square loop
In this section, we will learn about the Turtle Square loop in python turtle.
Loops are a fun way to simply learn and implement to see what it will draw.
Code:
In the following code, we have some fun using for loop in a program in which we design a shape of the square using the left() and forward() functions.
After running the above code, we have the following output which we generate with help of the left() and forward() functions using for loop.
Python turtle square spiral
In this section, we will learn about the Turtle Square Spiral in python turtle.
In this, we used a built-in module in python (turtle). It uses to draw on the screen using a turtle (pen). To move turtle here are some functions that we use to give shapes forward() and backward() etc.
Code:
In the following code, we have used a turtle module and using forward() and right() functions in which we define a length as len =10 and angle as angl=90 to form a spiral shape.
Output:
After running the above code, we can see how we can make a spiral shape by using forward() and right() functions.
Python turtle square size
In this section, we will learn about the Turtle Square Size in python turtles.
In this, we use a built-in module in python (turtle). A square is similar to a regular quadrilateral both have equal sides and equal angles of 90 degrees. And the size of the square depends upon the sides of the square.
Code:
In the following code, we create a screen inside the that we set the size of the square giving the width and height.
- size.setup(width=850, height=650) is a function used to set the height and width of the square.
- shape(‘square’) is used for making the shape of a square.
Output:
After running the above code we get the following output in which we see a square is made within a given size as mentioned in code where we take the width =850 and height =650 which depends on using size.setup() function.
Python turtle square root
In this section, we will learn about Turtle Square Root in Python turtle.
Before moving forward we should have a piece of knowledge about square root. The square root is that a number produces another number when it multiplies on its own.
Code:
In the following code, we import the turtle library and also import the math module for using mathematical functions.
- print(math.sqrt(6)) is used for printing the square root of 6.
- print(math.sqrt(16)) is used for printing the square root of 16.
- print(math.sqrt(7.5)) is used for printing the square root of 7.5.
Output:
After running the above code we get the following output in which we can see the square root of ‘6’, ’16’, and ‘7.5’.

Python turtle square inside a square
In this section, we will learn about squares inside a square in a python turtle.
As we know square has four equal sides and equal angles and each square has one more square inside it and it also has an equal side and equal angle.
Code:
In the following code, we import the turtle library import turtle import *, import turtle for drawing square inside a square.
tur.forward (length) function is used for moving the turtle in a forward direction with the given length.
Output:
After running the above code we get the following output in which we see the squares are drawn inside a square.
Python turtle square example
In this section, we will learn about the turtle square example in Python turtle.
In the Square example, we make a square shape with the help of a turtle we use the forward() and left() functions to make the perfect shape of the square.
Code:
In the following code, we import the turtle library for drawing the square with the help of the turtle.
- tur.forward(110) is used for moving the turtle in the forwarding direction by 110 units.
- tur.left(90) is used to turn the turtle in the left direction after moving forward.
Output:
In the following output, we see the square is drawn on the screen with the help of a turtle.
Python turtle fill square with color
In this section, we will learn about how to fill squares with color in Python turtle.
As we know we draw a square with the help of a turtle to look at the square we also fill color inside the square.
Code:
In the following code, we draw a square with the turtle and also filled color inside the square which gives the attractive look.
- tur.fillcolor(“cyan”) function is used to set the fill color.
- tur.begin_fill() function is used to start the filling color.
- tur.end_fill() function is used to ending the filling of the color.
Output:
After running the above code we get the following output in which we see a square that is filled with “cyan” color.
Python turtle draw multiple squares
In this section, we will learn about how to draw multiple squares in Python turtle.
As we can draw a square with the help of a turtle similarly we also draw multiple squares. Multiple squares create beautiful pictures on the screen.
Code:
In the following code, we create a screen inside the screen to draw multiple squares and these multiple squares give beautiful look to the screen.
Output:
After running the above code we get the following output in which we see multiple squares are drawn with the help of the turtle.
Python turtle repeating square
In this section, we will learn about How to draw repeating squares in python turtle.
Repeating square is that as we draw a single square and we want to draw more squares then we apply the loop after applying the loop repetition of the square is shown on the screen.
Code:
In the following code, we import turtle library from turtle import *, import turtle for draw repeating square.
- turtle.right(180) is used to turn the turtle 180 degrees to the right.
- turtle.speed(0) function is used to give speed to the turtle and ‘0 ‘ is the fastest speed.
Output:
After running the above code we get the following output in which we see the squares are drawn in repeating mode.
You check the following tutorials.
So, in this tutorial, we discussed Python Turtle Square and we have also covered different examples related to its implementation. Here is the list of examples that we have covered.
- Python turtle square function
- Python turtle square loop
- Python turtle square spiral
- Python turtle square size
- Python turtle square root
- Python turtle square inside a square
- Python turtle square example
- Python turtle fill square with color
- Python turtle draw multiple squares
- Python turtle repeating square

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
Как нарисовать квадрат в python
Блог веб разработки статьи | видеообзоры | исходный код

- Главная /
- PYTHON /
- tkinter python рисование
tkinter python рисование

Всем привет! Сегодня мы с вами познакомимся с элементом canvas который переводится как холст. Именно на данном холсте мы можем производить отрисовку различных фигур и текста. Итак, поехали!
Для того чтобы начать отрисовку в окне необходимо создать элемент canvas.
C помощью виджета canvas у нас создается холст. В него мы передали следующие параметры:
window — главное окно
width, height — ширина и высота холста
bg — заливка холста(gray — серый цвет)
cursor — курсор в фокусе холста(pencil — карандаш)

C помощью метода pack() мы выводим наш холст в главное окно.
Все теперь мы можем переходить к отрисовке. Начнем с простых линий.

Здесь мы создали две прямых линии. Для их создания воспользовались методом create_line() который принимает в себя следующие параметры.
Первые два параметра это координаты x,y первой точки начало отрезка.
Вторые два параметры это координаты x,y второй точки конец отрезка.
width — толщина линии.
fill — заливка, цвет линии(yellow — желтый).
Для того чтобы на холсте нарисовать прямоугольник или квадрат, нужно воспользоваться методом create_rectangle().

C помощью метода create_rectangle()мы нарисовали квадрат. Данный метод принимает в себя следующие параметры:
Первые два параметра координаты левого верхнего угла прямоугольника.
Вторые два параметра координаты правого нижнего угла прямоугольника.
fill — цвет заливки прямоугольника.
outline — цвет рамки прямоугольника.
Теперь переходим к отрисовке эллипсов и кругов.
Для того чтобы нарисовать круг или овал нам достаточно воспользоваться методом create_oval().

В основе отрисовки круга с помощью данного метода лежит отрисовка прямоугольника. То есть по сути мы отрисовываем невидимый квадрат куда может быть помещен в полную высоту и ширину квадрат или овал.
Данный метод принимает собой следующие аргументы:
Первые два аргумента в квадратных скобочках координаты x,y левого верхнего угла квадрата.
Вторые два аргумента в квадратных скобочках координаты x, y правого нижнего угла квадрата.
fill — цвет заливки овала.
Для отрисовки более сложных фигур треугольников, многоугольников, многогранников.
Мы можем воспользоваться методом create_polygon().

Здесь мы нарисовали треугольник. В качестве параметров данный метод принимает пары значений координат точек которые последовательно между собой соединяются прямыми.
Точек в разных координатах можно создавать сколько угодно. В результате можно нарисовать фигуру практически любой сложности. Свойство fill отвечает за цвет заливки фигуры, а outline за ее контур. Заметьте мы указали цвет заливки точно такой же как и цвет холста и в результате у нас получился эффект не закрашенной фигуры.
И напоследок рассмотрим отрисовку текста в canvas.

За отрисовку текста в canvas отвечает метод create_text(). В него передаются следующие параметры:
Первые два параметра координаты x, y расположения текста на холсте.
text — текст который мы хотим нарисовать
font — шрифт и размер текста
justify — выравнивание текста(слева, справа, по центру)
fill — цвет текста
Весь написанный за сегодня код выглядит так:
Отлично! Сегодня мы с вами познакомились с основами рисования canvas библиотеки tkinter.
Если у вас появились какие либо вопросы пишите в группу
или оставляйте их в комментариях к данной статье.
Также у меня есть канал на
где я каждую неделю публикую новые видео посвященные веб разработке. Так что переходите и будем развиваться вместе.
На этом у меня на сегодня все. Желаю вам успехов и удачи! Пока!
Оцените статью:
Статьи
Комментарии
Внимание. Комментарий теперь перед публикацией проходит модерацию
Евгений
Не подскажите как повернуть текст на 90 градусов чтобы подписать ось Y

Запись экрана
Данное расширение позволяет записывать экран и выводит видео в формате webm