Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting certain amount of time with Tkinter

I have a Tkinter program which I want to pause for 3 seconds. time.sleep doesn't work and the after method doesn't do exactly what I want to.

here is an example code:

from Tkinter import *
def waithere():
    print "waiting..."
root = Tk()

print "1"
root.after(3000,waithere)
print "2"

root.mainloop()

output:

1
2
*3 seconds*
waiting...

the output i want to have:

1
waiting...
*3 seconds*
2

thanks.

like image 378
Doron Sever Avatar asked Feb 03 '26 15:02

Doron Sever


2 Answers

Normally it's a very bad idea to have a GUI wait for something. That's imply not how event-based programs work. Or more accurately, GUIs are already in a perpetual wait state, and you don't want to block that with your own waiting.

That being said, tkinter has a way to wait until certain things happen. For example, you can use one of the "wait" functions, such as wait_variable, wait_window, or wait_visibility.

Assuming that you wanted waithere to do the waiting, you could use wait_variable to do the waiting, and after to set the variable after a given amount of time.

Here's the solution based on your original code:

from Tkinter import *
def waithere():
    var = IntVar()
    root.after(3000, var.set, 1)
    print("waiting...")
    root.wait_variable(var)

root = Tk()

print "1"
waithere()
print "2"

root.mainloop()

The advantage to using these methods is that your code is still able to respond to events while it is waiting.

like image 66
Bryan Oakley Avatar answered Feb 06 '26 05:02

Bryan Oakley


I found a way like that, i hope it helps you:

from tkinter import *

def waitToShow():
    index = 1
    while index < 11:
        l1.config(text=index)
        l1.after(1000)
        l1.update()
        index += 1

win = Tk()
l1 = Label(win)
l1.pack()

waitToShow()

win.mainloop()
like image 24
episometnal Avatar answered Feb 06 '26 07:02

episometnal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!