除非它可以执行自己的无限循环,否则Tkinter会挂起
root.mainloop。通常,您无法与Tkinter并行运行自己的无限循环。但是,有一些替代策略:
采用 after
after是Tkinter方法,它使目标函数在一定时间后运行。您可以通过使自身调用
after自身来使函数重复调用。
import tkinter#this gets called every 10 msdef periodically_called(): print("test") root.after(10, periodically_called)root = tkinter.Tk()root.after(10, periodically_called)root.mainloop()还有
root.after_idle,只要系统没有更多事件要处理,它就会执行目标功能。如果您需要比每毫秒一次的循环更快,则可能更可取。
采用 threading
该
threading模块允许您并行运行两段Python代码。使用此方法,可以使任何两个无限循环同时运行。
import tkinterimport threadingdef test_loop(): while True: print("test")thread = threading.Thread(target=test_loop)#make test_loop terminate when the user exits the windowthread.daemon = True thread.start()root = tkinter.Tk()root.mainloop()但请注意:从主线程以外的任何线程调用Tkinter方法可能会导致崩溃或导致异常行为。



