Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python tkinter animation sample
# coding=utf-8
from random import randint
def random_color():
colors = ["#00ff00", "#00ffff", "#0099ff", "#6600ff", "#cc33ff", "#ff33cc", "#ff5050", "#ff9933", "#ffff00",
"#99ff33", "#66ccff", "#990033"]
return colors[randint(0, len(colors)-1)]
class Shape(object):
def __init__(self):
self.x = 0
self.y = 0
self.width = 0
self.height = 0
self.color = "red"
self.speed = +2
def random_fill(self):
self.x = randint(20, 380)
self.y = randint(20, 180)
self.width = randint(10, 50)
self.height = randint(10, 50)
self.color = random_color()
def draw(self, canvas):
pass
class Rect(Shape):
def draw(self, canvas):
canvas.create_rectangle(self.x, self.y, self.x+self.width, self.y+self.height, fill=self.color)
class Circle(Shape):
def draw(self, canvas):
canvas.create_oval(self.x, self.y, self.x+self.width, self.y+self.height, fill=self.color)
def random_fill(self):
super(Circle, self).random_fill()
self.height = self.width
class Drawer:
def __init__(self, canvas):
self.canvas = canvas
self.shapes = []
self.animating = False
def add_rectangle(self):
rect = Rect()
rect.random_fill()
self.shapes.append(rect)
def add_circle(self):
circle = Circle()
circle.random_fill()
self.shapes.append(circle)
def redraw(self):
self.canvas.delete("all")
for shape in self.shapes:
shape.draw(self.canvas)
def next_state(self):
for shape in self.shapes: # Проходимся по всем фигурам
shape.y += shape.speed # меняем положение фигуры в соответствие со скоростью фигуры
if shape.y <= 0 or shape.y >= 180: # если фигура дошла верхнего или нижнего границ
shape.speed = -shape.speed # меняем скорость на противоположную
self.redraw() # перерисовываем все
# coding=utf-8
import Tkinter as tk # Подключаем библиотеку и называем ее коротко tk
from drawer import Drawer
window = tk.Tk() # Создаем новое окно
window.geometry("400x240") # Задаем окну размеры
window.title(u"Primitive shapes") # Задаем заголовок окна
canvas = tk.Canvas(window, width=400, height=200) # Создаем Canvas внутри window
canvas.pack() # Размещаем его по порядку сверху вниз
drawer = Drawer(canvas)
#
frame = tk.Frame(window, width=400, height=40) # Создаем Frame внутри window
frame.pack() # Размещаем его по порядку сверху вниз
shapes_text = tk.StringVar()
shapes_text.set("Rectangle")
option = tk.OptionMenu(frame, shapes_text, "Rectangle", "Circle")
option.pack(side=tk.LEFT)
def add_new_shape_click():
if shapes_text.get() == 'Rectangle':
drawer.add_rectangle()
elif shapes_text.get() == 'Circle':
drawer.add_circle()
drawer.redraw()
button = tk.Button(frame, text='Add', width=10, command=add_new_shape_click)
button.pack(side=tk.LEFT)
animate_btn_text = tk.StringVar()
animate_btn_text.set("Animate")
def on_animate_click():
drawer.animating = not drawer.animating # меняем свойство animating на обратную
if drawer.animating: # меняем текст кнопки
animate_btn_text.set("Stop")
else:
animate_btn_text.set("Animate")
animate() # запускаем метод для анимирования
def animate():
if drawer.animating: # если анимация включена
drawer.next_state() # меняем состония фигур на следующее
window.after(10, animate) # ставим таймер на 10 мс чтобы снова вызвать метод animate
button2 = tk.Button(frame, textvariable=animate_btn_text, width=10, command=on_animate_click)
button2.pack(side=tk.LEFT)
window.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment