How to pause program for some seconds

775 Views Asked by At

I am making a program in python (Tkinter) and somehow I am stuck between some confusion. I want to pause my program execution for some seconds, and also the execution pauses but not at correct time. My program looks like this:

from Tkinter import *
from time import *
root=Tk()
def login():
    g=str(ent.get())
    h=str(ent2.get())
    if h=='shubhank' and g=='shubhankt1':
        root2=Tk()
        root2.title("Shubhank Tyagi")
        root2.geometry('300x300')
        root2.wm_iconbitmap('st.ico')
        name=Label(root2, text='''Name: Shubhank Tyagi
    Age: 18 yrs
    Sex: Male
    Occupation: Student
    Designation: Intermediate''')
        name.pack()
    elif h=='divyansh' and g=='divyansht5':
        root2=Tk()
        root2.title("Divyansh Tyagi")
        root2.geometry('300x300')
        root2.wm_iconbitmap('st.ico')
        name=Label(root2, text='''Name: Divyansh Tyagi
    Age: 18 yrs
    Sex: Male
    Occupation: Student
    Designation: Intermediate''')
        name.pack()
    else:
        error=Label(root, text='Please provide correct info.')
        error.pack()
        sleep(5)
        error.pack_forget()
w=Label(root, text="Username", bg='Light Blue')
ent=Entry(root)
w2=Label(root, text="Password", bg='Light Blue')
ent2=Entry(root)
ent2.config(show=' ')

btn=Button(root, text='Click Me!', command=login)

This button (btn) calls the defined function. What I want is tht first tht error msg is printed.. and after sometime it gets deleted.. problem occurs tht after clicking the button, program is paused nd directly the error.pack_forget() functions gets executed.. and the error msg is never printed...

Please help me!

(I CAN ALSO PROVIDE THE ACTUAL PYTHON FILE, IF NEEDED)

1

There are 1 best solutions below

0
On

There are some fundamental things wrong with your program which are unrelated to your primary question, but which makes it hard to write a proper answer:

  1. You should never create more than a single instance of Tk.
  2. You should never call sleep in the main thread of a GUI.
  3. You're not calling mainloop, which is required for proper functioning.

The title of your question asks how to pause a GUI, but GUIs should never "pause" per se. When a GUI isn't actively doing anything it still needs to listen to events, because it is constantly getting events such as requests to redraw portions of itself, etc.

The body of your question asks how to hide a label after a few seconds, and mentions how you never see the message in the first place. The reason you never see it is the GUI never has a chance to respond to redraw events because you call sleep.

You can hide a message in the future by using generic widget method named after, which lets you run a function at some time in the future. For example:

def login():
    ...
    error = Label(...)
    error.pack(...)
    error.after(5000, error.pack_forget)
    ...