Анимация графики в python
Анимация в питон Пример анимации графики в модуле graphics в Python.
Чтобы графические объекты двигались в графическом окне Python, используется общий алгоритм анимации в цикле. В цикле for происходит рисование объекта, пауза, стирание объекта и изменение его координат. Чтобы нарисовать объект, мы ввели процедуру, в которую передаются координаты объекта и параметр видимости. Чтобы стереть объект, его нужно нарисовать цветом фона. Разберем структуру графической программы python с анимацией графических объектов
Импортируем все модули в программу питон.
from graphics import *
import time
Модуль питон time необходим для использования функции паузы time.sleep(время паузы)
win = GraphWin("Окно для графики", 400, 400)
win.setBackground('white')
Создаём окно для графики размером 400×400 пикселей. Окно будет называться «Окно для графики». Устанавливается цвет фона графического окна белыйВ нашей программе была создана процедура для отображения автомобиля по координатам. Были введены массивы для начальных координат машинок. Подробоно о работе с массивами в python
x = [10, 20, 30]
y = [100, 200, 300]
В программе была определена процедура рисования графического объекта в нашем примере автомобиля. Подробнее о процедурах в Python. Кузов и окно автомобиля рисуется с помощью многоугольника команды в модуле graphics в питон Polygon(), колёса рисуются с помощью команды рисования окружности в графическом модуле питон это команда Circle(). Кузов, окно, первое и второе колесо — это отдельные элементы, назовём их body, wheel1, wheel2 и window. Чтобы отобразить графические объекты в графическом окне в программе python необходимо использовать команду объект.draw(имя графического окна) Подробнее о работе с графикой в питон В процедуре рисования автомобиля , параметр flag определяет, будет ли рисоваться автомобиль или стираться с экрана. Если flag равен 0, то графический объект будет рисоваться цветом фона и его не будет видно в окне для графики, если flag равен 1, то графический объект будет рисоваться в окне для графики заданным цветом
def car(x, y, color, flag):
body = Polygon(
Point(x, y),
Point(x, y — 10),
Point(x + 10, y — 20),
Point(x + 30, y — 20),
Point(x + 40, y — 10),
Point(x + 50, y — 10),
Point(x + 50, y))
wheel1 = Circle(Point(x + 8, y + 4), 4)
wheel2 = Circle(Point(x + 42, y + 4), 4)
window = Polygon(
Point(x + 20, y — 12),
Point(x + 20, y — 18),
Point(x + 30, y — 18),
Point(x + 36, y — 12))
body.setOutline(color)
body.setFill(color)
wheel1.setFill("black")
wheel2.setFill("black")
window.setOutline("cyan")
window.setFill("cyan")
if flag == 1:
body.draw(win)
wheel1.draw(win)
wheel2.draw(win)
window.draw(win)
if flag == 0:
body.setOutline('white')
body.setFill('white')
wheel1.setFill("white")
wheel1.setOutline('white')
wheel2.setFill("white")
wheel2.setOutline('white')
window.setOutline("white")
window.setFill("white")
body.draw(win)
wheel1.draw(win)
wheel2.draw(win)
window.draw(win)
Полный текст программы на python анимации графических объектов
from graphics import *
import time
win = GraphWin("Окно для графики", 400, 400)
win.setBackground('white')
x = [10, 20, 30]
y = [100, 200, 300]
def car(x, y, color, flag):
body = Polygon(
Point(x, y),
Point(x, y — 10),
Point(x + 10, y — 20),
Point(x + 30, y — 20),
Point(x + 40, y — 10),
Point(x + 50, y — 10),
Point(x + 50, y))
wheel1 = Circle(Point(x + 8, y + 4), 4)
wheel2 = Circle(Point(x + 42, y + 4), 4)
window = Polygon(
Point(x + 20, y — 12),
Point(x + 20, y — 18),
Point(x + 30, y — 18),
Point(x + 36, y — 12))
body.setOutline(color)
body.setFill(color)
wheel1.setFill("black")
wheel2.setFill("black")
window.setOutline("cyan")
window.setFill("cyan")
if flag == 1:
body.draw(win)
wheel1.draw(win)
wheel2.draw(win)
window.draw(win)
body.setOutline('white')
body.setFill('white')
wheel1.setFill("white")
wheel1.setOutline('white')
wheel2.setFill("white")
wheel2.setOutline('white')
window.setOutline("white")
window.setFill("white")
body.draw(win)
wheel1.draw(win)
wheel2.draw(win)
window.draw(win)
for i in range(20):
car(x[0], y[0], 'green', 1)
car(x[1], y[1], 'green', 1)
car(x[2], y[2], 'green', 1)
time.sleep(1)
car(x[0], y[0], 'green', 0)
car(x[1], y[1], 'green', 0)
car(x[2], y[2], 'green', 0)
x[0] += 10
x[1] += 10
x[2] += 10
win.getMouse()
win.close()
Полезно почитать по теме графика в Python
Графика в Python
Графика черепашка turtle в Python
Python Tkinter Animation
In this tutorial, we are going to learn about Python Tkinter Animation. Here we will understand how to create animations using Tkinter in python and we will cover different examples related to animation. And we will also cover these topics
- Python tkinter animation
- Python tkinter loading animation
- Python tkinter timer animation
- Python tkinter matplotlib animation
- Python tkinter Simple animation
- Python tkinter Button animation
Python Tkinter Animation
In this section, we are learning about Python Tkinter Animation. By animation, we mean to create an illusion of moment on any object.
In the following code, we have taken two starting positions of “x” & “y” and give a window some width and height and inside that, we made a ball using canvas and to add a moment to the ball just inside a screen space what we created.
Code:
Here are some of the main highlights of the given code.
- Canvas.create_oval() is used to give the Oval shape to the ball.
- Canvas.move() = Motion of the ball
- time.sleep() it suspends execution for a given number of seconds.
Output:
After running the above code, we can see the following output in which a ball is changing its position. The ball is going up and down and showing an example of animation.
Python Tkinter Loading Animation
In this section, we are learning about python Tkinter loading animation. By loading, we mean the processing of any page or loading any data over the internet.
Code:
In the following code, we made a processing bar that runs after clicking on the run button and it shows us loading in page.
- Progressbar() is used to display the loading bar.
- mode=’determinate’ shows an indicator that moves starting point to the ending point.
Output:
After running the following code, we get the following output which shows us how loading is done in python Tkinter. Here in this, we can see when a user clicks on the “Run” button a loading of data is started on a page.
Python tkinter timer animation
In this section, we are learning about python Tkinter timer animation. By timer, we mean to set any time count for our alert to remember our task. The best example to understand about the timer is an alarm which we use in our common routine.
Code:
In the following code, we imported a time library that used to define hours, minutes & seconds. Here a user is setting up some time counter which does works like giving an alert after time is up.
Output:
After running the above code, we can see a user has set some timer for few seconds and it is working as per an order of timer.
Python tkinter matplotlib animation
Matplotlib is a Python library used for plotting graphs. It is an open-source library we can use freely. It is written in Python Language. Here is a tool that is specifically used to work on the function of matplotlib named “MATLAB“. In here Numpy is its numerical mathematical extension used to represent graphical values of its axis.
Code:
- plt.bar() is used to represent that the bar graph is to be plotted by using X-axis and Y-axis values.
- ptl.xlabel() is used to represent the x-axis.
- plt.ylabel() is used to represent the y-axis.
- plt.title() is used for giving the title to the bar graph.
Output:
After running the following code, we see the bar graph is generated. Here are the months and sales amount variables that represent the x-axis and y-axis values of data points and the bar are representing the total sale in a month. In the following gif, we can see the x-axis and y-axis are giving some values when we hover the mouse on a bar.
Python tkinter Simple animation
In the following section, we are learning about python Tkinter’s simple animation. In this, we have made a button through which clicking on that button changes the background color.
Code:
Ïn the following code we use a random library that gives a random choice to our options and at the top, we added a button with the text “click me” on that which changes the color of the background randomly.
- random.choice() return a list with randomly select color.
- ws.title is used for giving a title to the window.
- Button() is used to run the command to generate random colors in this.
Output:
After running the above code, we can run a simple animation with help of python Tkinter.
Python tkinter Button animation
in this section, we are learning about the Python Tkinter animation button.
We here use button animation as a feature that we can use in any gaming application or any similar application to turn on or to turn off that function. Here button is working like a normal switch which we used in our daily life to have access to switch on the light of the house.
Code:
In the above code, first, we have created a button object “a1” and then, we are using the IF statement to check the state of the button. In the end, we are using the state to change the behavior of the button to get the desired result.
Output:
After running the following code, we get the following output in which we see when we click on them the button will be disabled. And when we click on them again, the button will get enabled.
You may also like to read the following articles.
So, in this tutorial, we discuss Python Tkinter Animation. Here is the list of the examples that we have covered.
- Python Tkinter animation
- Python Tkinter animation tutorial
- Python Tkinter loading animation
- Python Tkinter timer animation
- Python Tkinter matplotlib animation
- Python Tkinter Simple animation
- Python Tkinter Button animation

Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.
Поворот и отображение изображения на 45, 90, 180, 270 градусов в Python
Чтобы повернуть изображение на угол с помощью Pillow, вы можете использовать метод rotate() для объекта Image, который вращает изображение против часовой стрелки.
Синтаксис
Синтаксис метода rotate() показан в следующем блоке кода.
- angle – в градусах против часовой стрелки;
- resample – необязательный фильтр передискретизации. Это может быть один из PIL.Image.NEAREST (использовать ближайшего соседа), PIL.Image.BILINEAR (линейная интерполяция в среде 2 × -2) или PIL.Image.BICUBIC (интерполяция кубическим сплайном в среде 4 × 4). Если опущено или если изображение имеет режим «1» или «P», устанавливается значение PIL.Image.NEAREST;
- expand – необязательное расширение. Если задано значение true, выходное изображение расширяется до размера, достаточного для размещения всего повернутого изображения. Если false или опущено, сделайте выходное изображение того же размера, что и входное изображение. Обратите внимание, что flag расширения предполагает вращение вокруг центра и отсутствие смещения;
- center – необязательный центр вращения (кортеж из двух элементов). Начало координат – левый верхний угол. По умолчанию это центр изображения;
- translate – необязательный перевод после поворота (двухкортежный);
- fillcolor – необязательный цвет для области за пределами повернутого изображения.
Пример 1: повернуть изображение на 45 градусов
В следующем примере мы повернем изображение на 45 градусов против часовой стрелки.


Размер исходного изображения сохраняется. Вы можете настроить размер выходного изображения в соответствии с поворотом.
Пример 2
В следующем примере мы настроим размер выходного изображения в соответствии с поворотом, используя параметр expand = True.

Пример 3: поворот на 90 градусов
Вы можете повернуть изображение на 90 градусов против часовой стрелки, задав угол = 90. Мы также указываем expand = True, чтобы повернутое изображение подстраивалось под размер вывода.

Пример 4: поворот на 180 градусов
В этом примере Python Pillow мы повернем изображение на 180 градусов.

Отображение изображения
Чтобы показать или отобразить изображение в Pillow, вы можете использовать метод show() для объекта изображения.
Метод show() записывает изображение во временный файл, а затем запускает программу по умолчанию для отображения этого изображения. По завершении выполнения программы временный файл будет удален.
Пример 1
В следующем примере мы прочитаем изображение и покажем его пользователю в графическом интерфейсе с помощью метода show().

В этом скрипте мы используем ПК с Windows, а программа «Фото» по умолчанию используется для открытия изображений BMP. Следовательно, метод show() отображал изображение с помощью программы Photos.
Пример 2
Вы можете отображать несколько изображений. Все изображения будут сложены, поскольку метод show() запускает отдельные экземпляры программы по умолчанию, которая отображает изображение на вашем компьютере.
В следующем примере мы прочитаем несколько изображений и покажем их пользователю в графическом интерфейсе с помощью метода show().