运行 持续使用 Tkinter 的长过程 (Python 2.7)

Run long process continously using Tkinter (Python 2.7)

在尝试了解 Tkinter 库的工作原理一段时间后,我 运行 遇到了问题。我编写的脚本使用多处理,并且因为脚本需要尽可能快,所以我最小化了进程之间的流量。这意味着完成大量任务大约需要一分钟。

(如果此任务中途中止,使用的文件将损坏)。

问题是我想要我的 GUI 中的停止按钮以正确的方式停止脚本。经过一些研究,我在寻找解决方案方面没有取得任何进展,所以也许你们中的一些人可以提供帮助。我基本上需要一种方法来在任务执行到一半时告诉脚本它必须停止,之后脚本将继续执行直到任务完成。

编辑: 我的脚本设置方式:

(缺少 Tkinter 部分,因为我还不知道解决方案)。

from multiprocessing import Pool

def Setup():
    #defines all paths of the files that are edited (and a whole lot more)

def Calculation(x, y, Primes):
    #takes an x and y value, calculates the value of that coordinate and determines
    #if the value is prime. Returns True of False, and the calculated value.

def Quadrant(List):
    #takes a huge list of coordinates that have to be calculated. These
    #coordinates (x and y) are passed to the 'Calculation' function, one by one.

    #Returns all the calculated coordinates and if they are prime or not (boolean)

if __name__ == "__main__":
    Filenames = Setup()
    Process = Pool(4)

    while True:
        #Loop the main bit of the code to keep expanding the generated image
        Input = [List of all coordinates, split into 4 quadrants (seperate lists) evenly]
        Output = Process.map(Quadrant, Input)

        #Combine all data and update list of primes

        #Detects if escape is pressed, stops if true.

我基本上是在寻找一种方法来停止上面的 while 循环,或者这个循环的替代方法。

我的意思基本上是任务必须停止,而不是突然中止。脚本必须等到它的任务完成,然后查看是否按下按钮来决定是否必须继续

我们没有您要回复的代码,所以如果您正在使用 while()(请注意,如果某些条件是 True/False,您也可以从函数发出 return ).

import time
from multiprocessing import Process, Manager

def test_f(test_d):
   """  frist process to run
        exit this process when dictionary's 'QUIT' == True
   """
   while not test_d["QUIT"]:
      print "     test_f", test_d["QUIT"]
      time.sleep(1.0)

def test_f2(name):
    """ second process to run.  Runs until the for loop exits
   """
    for j in range(0, 10):
       print name, j
       time.sleep(0.5)

    print "second process finished"

if __name__ == '__main__':
   ##--- create a dictionary via Manager
   manager = Manager()
   test_d = manager.dict()
   test_d["QUIT"] = False

   ##---  start first process and send dictionary
   p = Process(target=test_f, args=(test_d,))
   p.start()

   ##--- start second process
   p2 = Process(target=test_f2, args=('P2',))
   p2.start()

   ##--- sleep 2 seconds and then change dictionary
   ##     to exit first process
   time.sleep(2.0)
   print "\nterminate first process"
   test_d["QUIT"] = True
   print "test_d changed"
   print "data from first process", test_d

   ##---  may not be necessary, but I always terminate to be sure
   time.sleep(5.0)
   p.terminate()
   p2.terminate()

   """ Thanks Doug Hellmann
       Note: It is important to join() the process after terminating it.
       in order to give the background machinery time to update the.
       status of the object to reflect the termination
   """
   p.join()
   p2.join()