Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make the tkinter objects appear live?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading