- Draw Circle in Python Using turtle circle() Function
- Cool Patterns You Can Make With circle() in Python
- How to Draw a Circle with Different Colors in Python
- Other Articles You’ll Also Like:
- About The Programming Expert
- turtle — Turtle graphics¶
- Рисуем геометрические фигуры в Python с помощью Pillow
- Создание объекта Draw в Python
- Рисуем фигуры в Pillow: ellipse, rectangle и line
- Справочник по параметрам методов рисования
- Область рисования — xy
- Параметр fill — заполняем фигуру определенным цветом
- Параметр outline — цвет границ
- Параметр width — размер границ
- Рисование эллипса и прямоугольника в Python
- Draw Circle In Python Without Turtle
- Python Code To Draw Circle
Draw Circle in Python Using turtle circle() Function
To draw a circle in Python, we can use the circle() function from the Python turtle module.
import turtle t = turtle.Turtle() def draw_circle(radius): t.circle(radius) draw_circle(100)
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 shapes in Python. For example, we can draw rectangles and draw triangles easily in Python with the turtle module.
One other shape which is easy to draw with turtle is a circle.
The defining feature of a circle is the radius. To draw a circle in Python, we can use the turtle circle() function from the turtle module.
We can define a simple function which will take one argument, the radius of our circle, and make the circle.
Below is a simple example of how to use Python to create a circle.
import turtle t = turtle.Turtle() def draw_circle(radius): t.circle(radius) draw_circle(100)
Cool Patterns You Can Make With circle() in Python
There are a few cool patterns you can create with the Python turtle circle() function.
Below is the Python code for creating a spiral, and the output of the spiral with the turtle module.
import turtle t = turtle.Turtle() def draw_spiral(starting_radius, loops): for i in range(0, loops): t.circle(starting_radius + i, 60) draw_spiral(10, 100)
You can also make concentric circles easily with the circle() function. To make concentric circles, we make circles starting in the middle, and keep increasing the radius until the end.
Below is the Python code for creating concentric circles.
import turtle t = turtle.Turtle() def draw_concentric_circles(starting_radius, loops): for i in range(0, loops): t.circle(starting_radius*i) t.up() t.sety((starting_radius *i)*(-1)) t.down() draw_concentric_circles(10, 25)
How to Draw a Circle with Different Colors in Python
With turtle, we can easily add color to the shapes we create.
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 draw a green circle using pencolor() in Python.
import turtle t = turtle.Turtle() t.pencolor("green") t.circle(50)
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()
Hopefully this article has been helpful for you to learn how to draw a circle in Python.
Other Articles You’ll Also Like:
- 1. Read Pickle Files with pandas read_pickle Function
- 2. Python atan – Find Arctangent and Inverse Tangent of Number
- 3. Remove First and Last Character from String Using Python
- 4. Check if Word is Palindrome Using Recursion with Python
- 5. PROC REG Equivalent in Python
- 6. Generate Random Float Between 0 and 1 Using Python
- 7. for char in string – How to Loop Over Characters of String in Python
- 8. Using Python to Replace Backslash in String
- 9. Python Split List into N Sublists
- 10. Using Python to Calculate Sum of List of Numbers
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 — 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.
from turtle import * color('red', 'yellow') begin_fill() while True: forward(200) left(170) if abs(pos()) 1: break end_fill() done()
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.
Рисуем геометрические фигуры в 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() используются многочисленные координаты вместо двух точек, представляющих прямоугольную область.
Метод 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 . Если мы зададим четыре координата которые будут соответствовать квадрату, то у нас получится ровный круг.
Нарисуем небольшой смайл используя круги.
Draw Circle In Python Without Turtle
In this tutorial we will see how to draw a circle in python without turtle, To draw circle we will use the pygame library which is mainly used for game development in python but we will draw a circle with it.
Python Code To Draw Circle
import pygame import math pygame.init() # Set the size of the circle and the window size = width, height = 400, 400 screen = pygame.display.set_mode(size) screen_colr = 255, 255, 255 screen.fill(screen_colr) # Set the position and radius of the circle radius = 150 # Draw the circle for i in range(0, 360, 1): x = 200 + int(radius * math.cos(math.radians(i))) y = 200 + int(radius * math.sin(math.radians(i))) pygame.draw.circle(screen, (0, 0, 0), (x, y), 1) # Update the display pygame.display.flip() # Keep the window open until it is closed while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit()
Above is the code for drawing a circle using pygame module, you can run this program on your computer or use this web online compiler.
Before running this program you need to install pygame in your system you can do it by using the below command.
So when you run the program and you will see a new window opened and a circle drawn like below.
I hope you found this tutorial helpful and useful, Do share it with your friends who might be interested in this program, Want to know how can you draw a square in python without using the turtle module then refer here: Draw a square in python without turtle library.
Thanks for reading, Have a nice day 🙂