有没有办法编写命令,以便中止正在运行的函数调用?

时间:2010-09-01 18:38:23

标签: python tkinter abort

我有一个测量经过时间的小部件,然后在一定时间后执行命令。但是,如果窗口小部件已离开,我希望我希望它中止此函数调用而不执行该命令。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

使用threading模块并启动一个将运行该功能的新线程。

只是中止该功能是一个坏主意,因为您不知道在紧急情况下是否中断线程。你应该扩展你的功能:

import threading

class WidgetThread(threading.Thread):
     def __init__(self):
         threading.Thread.__init__(self)
         self._stop = False

     def run(self):
        # ... do some time-intensive stuff that stops if self._stop ...
        #
        # Example:
        #  while not self._stop:
        #      do_somthing()

     def stop(self):
         self._stop = True



# Start the thread and make it run the function:

thread = WidgetThread()
thread.start()

# If you want to abort it:

thread.stop()

答案 1 :(得分:0)

为什么不使用线程并停止呢?我认为在单线程程序中拦截函数调用是不可能的(如果没有某种信号或中断的话)。

另外,根据您的具体问题,您可能需要引入一个标志并在命令中检查它。

答案 2 :(得分:0)

不知道python线程,但一般来说,中断线程的方式是通过使用某种线程安全状态对象(可以从窗口小部件设置)和线程代码中的逻辑来检查状态对象的更改值和突破线程循环。