I´m trying to create a simple thing: a loop with a delay of x seconds between iterations, triggered by a Tkinter button command.
The obvious answer is to use time.sleep()
, however, this actually freezes the mainloop
process, avoiding other events to be captured.
I´ve searched and the recommendation is to use the tkinter.after()
method, however, I still can't make the loop take time between iterations.
Any help? Simplified code is below.
import tkinter as tk
import tkinter.scrolledtext as st
import time
# function to be activated by button
def do_some_action():
for i in range(10):
# just write some variable text to check if it is working
txt_bigtextlog.insert(tk.END,'Row text {} off 10\n'.format(i))
# tk.END to point the scrolling text to latest line
txt_bigtextlog.see(tk.END)
# I´ve tried w/o success (1000 is miliseconds):
# mywindowapp.after(1000)
# btn_action.after(1000)
time.sleep(1)
mywindowapp.update()
return()
# Create the application main window
mywindowapp = tk.Tk()
# create some label, just to visualize something
lbl_justsomelabel = tk.Label(text='Just some label here')
lbl_justsomelabel.grid(row=0,column=0,sticky='NSEW',padx=10,pady=10)
# create a button, just so simulate loop triggering
btn_action = tk.Button(text='Start process',command=do_some_action)
btn_action.grid(row=1,column=0,sticky='NSEW',padx=10,pady=10)
# create a scrolling text just to do some example iterable action
txt_bigtextlog = st.ScrolledText(mywindowapp,width = 30,height = 8)
txt_bigtextlog.grid(row=2,column = 0, columnspan=3,sticky='NSEW', pady = 10, padx = 10)
txt_bigtextlog.insert(tk.INSERT,'')
mywindowapp.mainloop()