Search code examples
pythondictionarytkinter

Using the name of file select by user into a dictionary in python


I have a basic code, and essentially what I am trying to do is ask user to select a file. The goal is to save the name of that file as a "value", and use it into a dictionary.

The code is below:

from tkinter import filedialog as fd

def select_study_file():
    study = fd.askopenfilename(initialdir=cur_dir, title='Select Study case')
    study = os.path.basename(study)
select_study_file()

config_dic = {"study_case" : study}

The expected output is:

config_dic = {"study_case" : "Name_of_the_file_selected}


Solution

  • You have a few errors in your code you can try something like this

    import os
    from tkinter import filedialog as fd
    
    def select_study_file():
        study = fd.askopenfilename(initialdir=".", title="Select Study case")
        return os.path.basename(study)
    
    study_file = select_study_file()
    config_dic = {"study_case": study_file}
    
    print(config_dic)