Tkinter askopenfilename path

Viewed 268

I am trying to build a Tkinter UI with a button where the user chooses a main file and based on information in that file, the script would get some information about some secondary files. Upon choosing the main file, I am trying to use the file path of the main file to get the file path of the secondary files. However, because I am calling a function "open_main_file()" twice, I get two dialog boxes where the user will have to choose the main file twice instead of once. How can I circumvent that?

My code looks like this:

import pandas as pd
from tkinter import *
from os.path import dirname
from tkinter import filedialog

root = Tk()

def open_main_file():
    return filedialog.askopenfilename()

def parse_main_file():
    return pd.read_parquet(open_main_file(), engine='pyarrow')

def get_some_ids():
    return parse_main_file()['some_ids'].iloc[0]

def get_list_of_other_files():
    other_files_path = dirname(dirname(dirname(open_main_file())))
    list_of_other_files = []
    for f in get_some_ids():
        list_of_other_files.append(glob.glob(other_files_path + '/identifier=' + str(f) + '/*'))
    return map(''.join, list_of_other_files)

myButton = Button(root, text='Open File...', command=get_list_of_other_files).pack()
root.mainloop()
1 Answers

try not to use a function in other functions. In this case, you are calling a function one time in another one, and one time in the main code. That is why you get file dialog 2 times. Use the returned item and give it to the next function. You can code like this:

import pandas as pd
from tkinter import *
from os.path import dirname
from tkinter import filedialog

root = Tk()

def open_main_file(): # This function is not necessary
    return filedialog.askopenfilename()

def parse_main_file(main_file_path):
    return pd.read_parquet(main_file_path, engine='pyarrow')

def get_some_ids(main_file_path):
    return parse_main_file(main_file_path)['some_ids'].iloc[0]

def get_list_of_other_files():
    main_file_path = filedialog.askopenfilename()
    other_files_path = dirname(dirname(dirname(main_file_path)))
    list_of_other_files = []
    for f in get_some_ids(main_file_path):
        list_of_other_files.append(glob.glob(other_files_path + '/identifier=' + str(f) + '/*'))
    return map(''.join, list_of_constituent_files)

myButton = Button(root, text='Open File...', command=get_list_of_other_files).pack()
root.mainloop()
Related