I have the following code:
from Tkinter import *
root = Tk()
def count():
for i in range(300):
Display.configure(text = 'The current number is: '+str(i))
Button = Button(root, text = 'Start', command = count)
Button.pack()
Display = Label(root)
Display.pack()
root.mainloop()
I want it that after clicking the 'Start' button to display the current number during counting, but it won't work. It only displays the number after it finishes counting, so after the counting in only shows: "The current number is: 299". (The point of this would be that I want to know how to display the current state of the code. (I need to make an application that gathers specific files than copies it to specific places and I want it to display what file it is currently copying. The application works with the works the exception of displaying the current file. I tried to test the displaying with the code above.)
In your example code, the problem is that, first of all, the display has no change to update inside your loop, and second, if it would update, it would be to fast to see any other number than the last.
A simple fix is to call root.update_idletasks()
to give the display a change to update.
from Tkinter import *
import time
root = Tk()
def count():
for i in range(300):
Display.configure(text = 'The current number is: '+str(i))
root.update_idletasks()
time.sleep(0.01) # just to see something
Button = Button(root, text = 'Start', command = count)
Button.pack()
Display = Label(root)
Display.pack()
root.mainloop()
A probably better way is to use a coroutine (which I wrapped into a decorator here) and after_idle
:
import time
from Tkinter import *
root = Tk()
def updatesdisplay(func):
def driver(iterator):
try: next(iterator)
except StopIteration: pass
else: root.after_idle(driver, iterator)
def wrapped():
driver(func())
return wrapped
@updatesdisplay
def count():
for i in range(300):
time.sleep(0.005) # just to see something
Display.configure(text = 'The current number is: '+str(i))
yield # chance to update display here
Button = Button(root, text = 'Start', command = count)
Button.pack()
Display = Label(root)
Display.pack()
root.mainloop()