虽然如此......没有窗户崩溃

时间:2015-03-27 12:05:34

标签: python python-2.7 tkinter

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

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

当我检查python控制台时,一切都很完美,但在窗口中按钮冻结,窗口崩溃...... 我的问题是:有没有办法调用这些函数而不会崩溃?这是我第一次遇到这样的问题,我使用kivy遇到同样的问题,似乎无法在GUI程序上完成?

2 个答案:

答案 0 :(得分:2)

您的永无止境的函数在与GUI相同的线程中执行。由于您的函数没有返回,因此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()。

答案 1 :(得分:2)

在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系统提供了一些急需的时间来重绘其窗口并清除其事件队列,因此它不会锁定。


您也可以使用after_idle,类似于after,除非它在GUI系统不再忙碌时执行您的功能。