-1

so i have a simple problem but i have no idea what's wrong so have a look:

from tkinter import *
from time import sleep
root = Tk()
l1 = Label(root, text="Ok")
l1.pack()
sleep(5)
l2 = Label(root, text="Great")
l2.pack()
sleep(10)
l3 = Label(root, text="Nice")
l3.pack()
root.mainloop()

All i wanted to do is make a window, and then display those label's one after another so the window would pop up with just l1 and after 5s the l2 would also appear and then after another 5s l3 should show up. Instead i don't see this window at all for 10s and then it appear with all the label's at once. Can someone help me fix this ?

SuperShoot
  • 9,880
  • 2
  • 38
  • 55
Goriss
  • 147
  • 2
  • 3
  • 9
  • 1
    The main window will not be updated until the main loop is called. If you want the labels to appear one after another with delays, learn how to use `root.after()`. – DYZ Jul 18 '17 at 03:51
  • Can you give me an example as to how it should look like? – Goriss Jul 18 '17 at 04:00
  • 1
    How about googling a tutorial? – DYZ Jul 18 '17 at 04:00

1 Answers1

2

First of all, dont use from tkinter import *.

From this answer :

from Tkinter import * imports every exposed object in Tkinter into your current namespace. import Tkinter imports the "namespace" Tkinter in your namespace and import Tkinter as tk does the same, but "renames" it locally to 'tk' to save you typing

you want only one object of a module, you do from module import object or from module import object as whatiwantittocall

from module import * is discouraged, as you may accidentally shadow ("override") names, and may lose track which objects belong to wich module.

Now for your question, you need to use root.after(timeInMillisecond, functionToCall) and add the label in the function:

import tkinter as tk
root = tk.Tk()

button = tk.Button(root, text="Quit", command=root.destroy)
button.pack()

l1 = tk.Label(root, text="Ok")
l1.pack()


def add_label():
    l1 = tk.Label(root, text="Ok")
    l1.pack()
    root.after(500, add_label)

root.after(500, add_label)
root.mainloop()

PS : if someone with 1500+ reputation could add a tags "root.after" or something like this, it's the main point of the question