问题描述
我正在尝试运行 While 循环以不断做某事.目前,它所做的只是让我的程序崩溃.
I am trying to run a While Loop in order to constantly do something. At the moment, all it does is crash my program.
这是我的代码:
import tkinter
def a():
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=800, height=600)
while True:
print("test")
a()
它会循环print
语句,但实际画布拒绝打开.
It will loop the print
statement, however the actual canvas refuses to open.
是否有任何可行的无限循环可以与 Tkinter 一起使用?
额外信息当我删除 While True
语句时,画布再次出现.
Extra InformationWhen I remove the While True
statement, the canvas reappears again.
推荐答案
Tkinter 挂起,除非它可以执行自己的无限循环 root.mainloop
.通常,您不能与 Tkinter 并行运行自己的无限循环.不过,还有一些替代策略:
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
是一个Tkinter 方法使目标函数在一定时间后运行.您可以通过使函数自身对自身调用 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()
还有root.after_idle
,一旦系统没有更多事件要处理,它就会执行目标函数.如果您需要循环速度超过每毫秒一次,这可能更可取.
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
模块允许您运行并行的两段 Python 代码.使用这种方法,你可以让任意两个无限循环同时运行.
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()
但请注意:从主线程以外的任何线程调用 Tkinter 方法可能会导致崩溃或导致异常行为.
But take caution: invoking Tkinter methods from any thread other than the main one may cause a crash or lead to unusual behavior.
这篇关于python - While 循环导致整个程序在 Tkinter 中崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!