I have difficulties with my rather simple (I'd say) code. My goal: I want to create an app that takes single lines of a .txt and adds them them each to a text box (TKinter), with a few seconds in between.
def startRoutine():
file = open(filename, "r")
all_lines_variable = file.readlines()
for i in range(0, len(all_lines_variable)):
root.after(1000, t.insert(tk. END, all_lines_variable[i]))
(t is the textbox, filename opens the directory)
What I think I'm doing: wait a second, then add the string to the textbox. Repeat with the next line until there aren't any lines left in the txt.
What I'm acutually doing: Waiting 1 second times each line AND THEN printing all the lines. My question would thus be: How do I acutally make the program wait in between the inserts?
Thank you very much!
after
does not pause the program like time.sleep
does, it just schedules something to be run later and keeps going. So all your lines are scheduled to run in 1000 milliseconds. To do what you want you can either use the i
variable to give each line a time 1000 ms apart:
from functools import partial
def startRoutine():
file = open(filename, "r")
all_lines_variable = file.readlines()
for i in range(0, len(all_lines_variable)):
root.after(1000 * i, partial(t.insert, tk.END, all_lines_variable[i]))
Or (more common) you can make a second function to act as the loop, which waits until it's called to schedule the next loop:
def loop(lines):
if lines:
t.insert(tk.END, lines.pop(0))
root.after(1000, loop, lines)
def startRoutine():
file = open(filename, "r")
all_lines_variable = file.readlines()
loop(all_lines_variable) # start loop