How to make the tkinter objects appear live?

Question:

i am creating the balls like this

from tkinter import *
import random 
import time 
colors = ["red", "blue", "purple", "green", "violet", "black"]
tk = Tk()
tk.title("Random balls")
canvas = Canvas(tk, width = 600, height = 600, bg = "white")



for i in range(10):
    x0 = random.randint(0, 600)  
    y0 = random.randint(0, 600)
    i=40
    colors = ["red", "blue", "purple", "green", "violet", "black"]
    for o in range(5):
        x0 = x0 + 10
        y0 = y0 + 10
        x1 = x0 + i
        y1 = y0 + i
        canvas.create_oval(x0, y0, x1, y1, fill=random.choice(colors), tag="circle")
        canvas.pack()
        i=i+8
canvas.pack()

This program is creating growing balls with random start positions, and random color.

Hello, how to make the tkinter objects(balls for example) appear on the tkinter window live(i want to see they appearing on thw windows, and not start the tkinter and the objects are already on the windows)?
Thanks

Asked By: Victor Kemp

||

Answers:

You can tell your tkinter application to call a function after x time in milliseconds. This function can contain the code for creating the circles:

from tkinter import *
import random 
import time

def create_circles():
    for i in range(10):
        x0 = random.randint(0, 600)  
        y0 = random.randint(0, 600)
        i=40
        colors = ["red", "blue", "purple", "green", "violet", "black"]
        for o in range(5):
            x0 = x0 + 10
            y0 = y0 + 10
            x1 = x0 + i
            y1 = y0 + i
            canvas.create_oval(x0, y0, x1, y1, fill=random.choice(colors), tag="circle")
            canvas.pack()
            i=i+8
            
            canvas.update() # Here you need to update the canvas for the new circle to show
            time.sleep(0.1) # Here you can put a delay between the appearence of the individual circles

#colors = ["red", "blue", "purple", "green", "violet", "black"]
tk = Tk()
tk.title("Random balls")
canvas = Canvas(tk, width = 600, height = 600, bg = "white")
canvas.pack()
tk.after(1000, create_circles)
tk.mainloop()
Answered By: sunnytown
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.