while true do...没有 window 崩溃

while true do... without the window crashing

我有 tgis 问题,我的 tkinter window 中有一个按钮调用 python 函数,例如:

While True :
    n=n+1
    print n #to check if the function is really called upon button press

当我检查 python 控制台时,一切正常,但在 window 中,按钮冻结并且 window 崩溃... 我的问题是:有没有一种方法可以在不崩溃的情况下调用这些函数?这不是我第一次遇到这样的问题,我在使用 kivy 时遇到了同样的问题,似乎无法在 GUI 程序上完成?

您永无止境的功能与 GUI 在同一线程中执行。由于您的函数没有 return,因此 GUI 永远不会刷新。它被冻结了。

您可以在单独的线程中启动您的 while True 函数,让 GUI 定期刷新并捕获取消按钮或退出命令。然后 GUI 可以将 end_function 变量设置为 True。在您的循环中,检查变量并在需要时中断。

参见 help about threading

未经测试的代码来说明这个想法:

from threading import Thread

class Worker(Thread):

    def __init__(self):
        self._end_function = False

    def stop(self):
        self._end_function = True

    def run(self):
        while not self._end_function:
            print("I'm working hard.")

在您的主代码中,实例化 Worker,并在按下按钮时调用 Worker.start()(不是 Worker.run(),请参阅帮助。)。然后,根据用户操作(取消、退出...),调用 Worker.stop().

在Tkinter中,传统的做法是使用after,这会导致目标函数在一定时间后执行。

def some_function():
    global n
    n += 1
    print n
    root.after(100, some_function)

root.after(100, some_function)

现在 some_function 将每 100 毫秒执行一次。这些周期性延迟为 GUI 系统提供了一些急需的时间来重绘其 windows 并清除其事件队列,因此它不会锁定。


您也可以使用 after_idle,它类似于 after,只是它会在 GUI 系统不再繁忙时立即执行您的功能。