sokorota
sokorota

Reputation: 19

How to make the movement of the circles smoother?

I would like to make the movement of the three randomly generated circles smoother. Can anyone help me with that? Thank you in advance :) Here is my current code:

import tkinter
from time import sleep
from random import randrange


class Circle:
    def __init__(self, color):
        a = randrange(250)
        b = randrange(250)

        self.color = color
        self.id = canvas.create_oval(a,b,a+40,b+40, fill=self.color)

    def move(self):
        canvas.move(self.id, 5,15)

window = tkinter.Tk()
window.geometry("500x400")
canvas = tkinter.Canvas(width=400, height=300)
canvas.pack()

circle1 = Circle('red')
circle2 = Circle('yellow')
circle3 = Circle('blue')

while(3):
    canvas.update()
    sleep(1)
    circle1.move()
    circle2.move()
    circle3.move()


window.mainloop()

Upvotes: 1

Views: 140

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36702

Use tkinter.after instead of sleep, and let the mainloop do its work, instead of a while loop and canvas.update().

something like this:

import tkinter
from random import randrange


class Circle:
    def __init__(self, color):
        a = randrange(250)
        b = randrange(250)

        self.color = color
        self.id = canvas.create_oval(a,b,a+40,b+40, fill=self.color)

    def move(self):
        canvas.move(self.id, 1, 1)

def move_circles(circles):
    for circle in circles:
        circle.move()
    window.after(10, move_circles, circles)

window = tkinter.Tk()
window.geometry("500x400")
canvas = tkinter.Canvas(width=400, height=300)
canvas.pack(expand=True, fill=tkinter.BOTH)

circle1 = Circle('red')
circle2 = Circle('yellow')
circle3 = Circle('blue')

circles = [circle1, circle2, circle3]

move_circles(circles)


window.mainloop()

Upvotes: 1

Related Questions