I am trying to run a While Loop in order to constantly do something. At the moment, all it does is crash my program.
Here is my code:
import tkinter
def a():
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=800, height=600)
while True:
print("test")
a()
It will loop the print
statement, however the actual canvas refuses to open.
Are there any viable infinite loops that can work alongside Tkinter?
Extra Information
When I remove the While True
statement, the canvas reappears again.
Tkinter hangs unless it can execute its own infinite loop, root.mainloop
. Normally, you can't run your own infinite loop parallel to Tkinter's. There are some alternative strategies, however:
after
after
is a Tkinter method which causes the target function to be run after a certain amount of time. You can cause a function to be called repeatedly by making itself invoke after
on itself.
import tkinter
#this gets called every 10 ms
def periodically_called():
print("test")
root.after(10, periodically_called)
root = tkinter.Tk()
root.after(10, periodically_called)
root.mainloop()
There is also root.after_idle
, which executes the target function as soon as the system has no more events to process. This may be preferable if you need to loop faster than once per millisecond.
threading
The threading
module allows you to run two pieces of Python code in parallel. With this method, you can make any two infinite loops run at the same time.
import tkinter
import threading
def test_loop():
while True:
print("test")
thread = threading.Thread(target=test_loop)
#make test_loop terminate when the user exits the window
thread.daemon = True
thread.start()
root = tkinter.Tk()
root.mainloop()
But take caution: invoking Tkinter methods from any thread other than the main one may cause a crash or lead to unusual behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With