Python Tkinter How to Update a Text Widget in a for Loop

How to Update text in Tkinter Label/Canvas widget using for loop?

import tkinter as tk
root = tk.Tk()
root.attributes("-fullscreen", True)
root.bind("<F11>", lambda event: root.attributes("-fullscreen", not root.attributes("-fullscreen")))
root.bind("<Escape>", lambda event: root.attributes("-fullscreen", False))
root.bind("<F1>", lambda event: os.exit(0))

w = tk.StringVar()

labelFlash = tk.Label(root, bg='Black', width=root.winfo_screenwidth(), height=root.winfo_screenheight(),
anchor="center", text="Sample", fg="White", font="Times " , textvariable=w)
labelFlash.pack()
MSG="Hello World"
str_list=[]
for i in range(len(MSG)):
str_list.append(MSG[:i+1])
words=str_list


indx=0
def update():
global indx
if indx>=len(words):
indx=0
w.set(words[indx])
labelFlash.config(text=words[indx])
indx+=1
root.after(500, update)#500 ms


update()
root.mainloop()

updating text after running mainloop in tkinter

The code after mainloop() gets called only after your applications is closed. So after the application is closed, the method is called, but the widgets used in the method is destroyed. So change your code to:

monitor = Monitor()
monitor.loginfo()
monitor.root.mainloop()

This way, the function is called before you exit the GUI. Think of mainloop() as a while loop that keeps updating till the window is closed. Technically saying mainloop() is same as:

while True: # Only exits, because update cannot be used on a destroyed application
root.update()
root.update_idletasks()

Edit:
Since you wanted a delay, you have to add a button or something that calls this method while the GUI is active, an example is to use after to show the function after some time, like:

monitor = Monitor()

monitor.root.after(1000,monitor.loginfo) # Cause a delay of 1 second or 1000 millisecond

monitor.root.mainloop()

insert data into text widget in a For loop, tkinter python3

You need to call update on the widget you are adding new data to, for it to refresh and show the new values after each iteration. This is as the Tk mainloop will normally catch the new information on your widget and update it, but when you are in a loop such as this, it cannot check until after the loop is finished.

If root is what you define to be Tk(), then you can call root.update(), or on the actual widget itself. This would go at the end of your for loop.



Related Topics



Leave a reply



Submit