Используйте модуль 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()