Search code examples
pythontkintertcltk-toolkittkinter-text

How can I actually execute a 'while True' loop code while there is a 'mainloop()' in the code?


I am sorry if my question is not understandable. Anyways, I have this code:

from tkinter import *
root = Tk()
root.title("My Window")

# Adding a text widget thing.
text = Text(root, foreground='black', background='white', font=("Consolas", 16))
text.pack(expand=1, fill=BOTH)

# a while true loop.
while True:
    text.delete(1.0, END)
    text.insert(END, "This is a text in a loop")

# Calling the Python tkinter's mainloop.
root.mainloop()

Each time I try to run the code above, it doesn't show the Window, instead, it runs the code in the while True loop.

So the main question is, Is there a way to make Python show the window (I mean execute the code root.mainloop(), and then execute the while True loop's code?

Any help or answers would be much appreciated!
Thank you!


Solution

  • You should try to avoid this, but you can use a recursion loop.

    make a function called "myloop" and repeat it, like so, and then call it just before mainloop:

    def myloop():
       <code>
       root.after(1, myloop) #repeats the function again 1 1000th of a second after it finishes
    
    
    #----- down by where you're calling mainloop-----
    
    
    root.after(1, myloop)
    root.mainloop()