Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

python - While Loop causes entire program to crash in Tkinter

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

Use 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.

Use 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...