Python告诉工作线程停止

时间:2018-06-10 13:07:26

标签: python for-loop tkinter while-loop python-multithreading

Tkinter正在主线程上运行,而工作线程上正在运行一个进程。在Tkinter窗口中,如果用户点击“停止”'按钮,工人应该停下来。

我正在使用while循环,由于某种原因,它不起作用。

请检查以下代码。

from threading import Thread
import time
import Tkinter as tk

class status:
    STOP = False

def stop():
    print 'User request to STOP the work'
    status.STOP = True

def worker():
    print 'worker starts'
    while not status.STOP:
        for i in xrange(10):
            print i
            time.sleep(1)
        print 'worker finishes'
    if status.STOP:
        print 'worker was interrupted'
        # wrapping stuff up.....
    else:
        print 'worker finished without interruption'

if __name__ == '__main__':
    root = tk.Tk()
    tk.Button(root, text="STOP", command=stop).pack()
    Thread(target=worker).start()
    root.mainloop()

编辑1: 我想我知道为什么它不起作用。如果我理解正确,则在完成整个循环后检查 while 循环中的条件。但是,我仍然不知道如何处理这种情况。

编辑2: @smoggers的答案(将if status.STOP in the放在xrange(10)`循环中的i)在技术上会起作用,但是如果工作过程要复杂得多呢?

请参阅以下新工作人员的代码'功能:

def worker():
    print 'worker starts'
    while not status.STOP:
        for i in xrange(10):
            print i
            time.sleep(1)
            print 'do some complex stuff'
            time.sleep(1)
            print 'do more complex stuff'
            time.sleep(1)
        print 'worker finishes'
    if status.STOP:
        print 'worker was interrupted'
        # wrapping stuff up.....
    else:
        print 'worker finished without interruption'

我希望能够检查状态,而运行每行代码。解决它的一种愚蠢的非编程方式是将if status.STOP: break放在 for循环中代码的每一行。如何巧妙地发挥同样的效果?

0 个答案:

没有答案
相关问题