Search code examples
pythonpython-2.7tkinterpython-multiprocessing

Spawning a Process launches another instance of Tkinter - Python 2


I'm trying to implement multiprocessing to a program I made for my job, and I'm running into issues. Please see the simplified code below; when I launch a process, it launches another instance of the gui; when I close that instance, the cpu_intensive function is processed. It's my first time using Tkinter and threads and processes so there might be more than one problem in there ;-) Thanks for looking into this:

from Tkinter import *
from threading import Thread
from multiprocessing import Process, Queue


source_queue = Queue()


def thread_launch():
    """launches a thread to keep the gui responsive"""
    thread1 = Thread(target=process_engine)
    return thread1.start()


def process_engine():
    """spawns processes and populates the queue"""
    p1 = Process(target=cpu_intensive, args=(source_queue,))
    p1.start()

    p2 = Process(target=cpu_intensive, args=(source_queue,))
    p2.start()

    for i in range(10):
        source_queue.put(i)
        print "Added item", i, "to queue"

    source_queue.close()
    source_queue.join_thread()
    p1.join()
    p2.join()


def cpu_intensive(item_toprocess):
    """function to be multiprocessed"""
    print "Processed: item", item_toprocess.get()


class Application:

    def __init__(self, master):
        """defines the gui"""
        self.master = master
        self.process_button = Button(self.master,
                                     text="Process",
                                     command=thread_launch)
        self.process_button.pack(padx=100, pady=100)


def __main__():
    """launches the program"""
    root = Tk()
    app = Application(root)
    root.mainloop()


if __name__ == __main__():
    __main__()

Solution

  • Try:

    if __name__ == "__main__":
    

    instead. The previous version was calling main but checking the returned value (None in this case). The problem was (I suspect you are on Windows) that the child process was also calling main in the if statement.