Home > Back-end >  Calling Tkinter before Multiprocessing causes multiple windows?
Calling Tkinter before Multiprocessing causes multiple windows?

Time:12-11

I'm trying to use tkinter to process a larger file into several smaller files using python. What happens is I run the code from a batch file, I get prompted for the file, I select the file and hit ok, python then opens 8 more file dialogs. How do I get my code to accept my initial input? As far as I can see, this shouldn't happen, because the file dialog is not in the multipro def. What is going on?

code is something like:

import tkinter, multiprocessing
from tkinter import filedialog

filename = filedialog.askopenfilename()

def multipro(num):
     code.split(filename, num)
     newfilename = filename   str(num)   fileextension
     code.save(newfilename)

def MCprocess():
    pool = multiprocessing.Pool(8)
    pool.map(multipro, num)

if __name__ == '__main__':
    num = list(range(1,10))
    MCprocess()
    sys.exit()

CodePudding user response:

You need to put the filename = filedialog.askopenfilename() inside the if __name__ == '__main__': so it's not executed by each subtask.

Since each process runs in its own memory-space, global variables shared among the processes aren't possible. If feasible, the simplest thing to do is pass the data as argument(s) to each of the processes. Since the function argument passed to Pool.map() can only accept a single argument, I've used functools.partial to create a temporary function based on multipro() to pass it that has the filename already provided to it.

Here's a more comprehensive answer. I've provided many of the undefined things you left out of the code in your question (so I could test the code in my answer).

from functools import partial
from pathlib import Path
import sys


def multipro(filename, num):
    print(f'in multipro({filename=!r}, {num=})')
    fileextension = Path(filename).suffix

    code.split(filename, num)
    newfilename = filename   str(num)   fileextension
    code.save(newfilename)

def MCprocess(filename, nums):
    func = partial(multipro, filename)
    with multiprocessing.Pool(8) as pool:
        pool.map(func, nums)


if __name__ == '__main__':

    import tkinter, multiprocessing
    from tkinter import filedialog

    root = tkinter.Tk()
    root.withdraw()
    root.update()
    filename = filedialog.askopenfilename()
    root.destroy()

    if filename:  # User selected file?
        nums = list(range(1,10))
        MCprocess(filename, nums)

  • Related