Простое рисование с помощью черепашки¶
У неё есть функции в стиле 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
Prerequisite: Turtle Programming Basics
turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Drawing Square:
Python3
Input :
Output :
Second approach (Using Loop) :
Python3
Input :
Output :
Drawing Rectangle:
Python3
Input :
Output :
Second approach (Using Loop) :
Python3
Input :
Output :
Since as of now, you must have learned how to draw various basic geometrical illustrations like circle, square, rectangle. So, let’s implement this knowledge to build something which you can really use in building games like let’s draw a human being using the basic knowledge of geometrical knowledge.
Рисуем геометрические фигуры в 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 . Если мы зададим четыре координата которые будут соответствовать квадрату, то у нас получится ровный круг.
turtle — Turtle graphics¶
Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle , give it the command turtle.forward(15) , and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25) , and it rotates in-place 25 degrees clockwise.
Turtle can draw intricate shapes using programs that repeat simple moves.
By combining together these and similar commands, intricate shapes and pictures can easily be drawn.
The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.
It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The object-oriented interface uses essentially two+two classes:
The TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its constructor needs a tkinter.Canvas or a ScrolledCanvas as argument. It should be used when turtle is used as part of some application.
The function Screen() returns a singleton object of a TurtleScreen subclass. This function should be used when turtle is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible.
All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface.
RawTurtle (alias: RawPen ) defines Turtle objects which draw on a TurtleScreen . Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw.
Derived from RawTurtle is the subclass Turtle (alias: Pen ), which draws on “the” Screen instance which is automatically created, if not already present.
All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented interface.
The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle . They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.
To use multiple turtles on a screen one has to use the object-oriented interface.
In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.