Luka1
Luka1

Reputation: 71

Problems with making time delay

I am trying to displey a few labels for exact amount of time and than forget them. I tried with sleep() and time.sleep(), but the program started after time I have defined and than executes lines. Here is part of my program:

from time import sleep
from tkinter import*
from tkinter import ttk
root = Tk()
root.geometry('700x700+400+100')
root.overrideredirect(1)
myFrame=Frame(root)
label1=Label(myFrame, text='Warning!', font=('Arial Black', '26'), fg='red')


myFrame.pack()
label1.pack()

sleep(10)



myFrame.pack_forget()
label1.pack_forget()

But when I run the program it wait for 10 seconds and than executes the lines (frame and label are packed and than immediatly forget).

I hope it is clear, what problem I have.

Upvotes: 1

Views: 126

Answers (1)

miradulo
miradulo

Reputation: 29740

Use the Tkinter after method instead of time.sleep(), as time.sleep() should almost never be used in a GUI. after schedules a function to be called after a specified time in milliseconds. You could implement it like this:

myFrame.after(10000, myFrame.pack_forget)
label1.after(10000,label1.pack_forget)

Note that after does not ensure a function will occur at precisely the right time, it only schedules it to occur after a certain amount of time. As a result of Tkinter being single-threaded, if your app is busy there may be a delay measurable in microseconds (most likely).

Upvotes: 2

Related Questions