Load csv file based on selection
<p>Before I put my question here I've looked everywhere and tried everything to find a solution but couldn't find one.</p>

<p>I've build a simple GUI in Tkinter. The goal is to first make a selection based on choises in a dropdown box.
In my example the subject is "Tennis".</p>

<p>My goal is that the user can first select the "surface" on which the tennis match is played on. We have 3 choises. Hard Court, Clay Court or Grass Court.</p>

<p>Based on the made selection I want a different csv file to be loaded.</p>

<ul>
<li>The Hard Court file is called "match_stats_atp_.csv" </li>
<li>The Clay Court file is called "match_stats_atp_1.csv" </li>
<li>The Grass Court file is called "match_stats_atp_10.csv"</li>
</ul>

<p>Each csv file holds data based on the specifiek tennis surface.</p>

<p>My question now is, how do I load the csv file based on the made selection in the fist dropdown box?
The csv files are  in the same directory as my script.</p>

<pre><code>from Tkinter import *
import ttk
import csv

master = Tk()
master.option_add("*Font", "{Bodoni MT} 8")

content = ttk.Frame(master, padding=(12, 12, 12, 12))
frame = ttk.Frame(content, borderwidth=5, relief="groove", width=300, height=100)
content.grid(column=0, row=0, sticky=(N, S, E, W))
frame.grid(column=0, row=0, columnspan=4, rowspan=2, sticky=(N, S, E, W))
text = Text(content, height=8, width=13)
text.grid(row=0, column=4, columnspan=2, rowspan=2, sticky=(N, S, E, W))

v1player1 = StringVar()
v2player1 = StringVar()

c_player1 = Label(frame, text="Service Points Win %:").grid(row=6, column=1, sticky='w')
cc_player1 = Entry(frame, text="value", textvariable=v1player1, justify='center', width=10).grid(row=6, column=2)
d_player1 = Label(frame, text="Return Points Win %: ").grid(row=7, column=1, sticky='w')
dd_player1 = Entry(frame, text="value", textvariable=v2player1, justify='center', width=10).grid(row=7, column=2)


def new_selection_surface(event):
    return surface()

surface_types = ['ATP Hard Court', 'ATP Clay Court', 'ATP Grass Court']

box_value_surface = StringVar()
box = ttk.Combobox(frame, textvariable=box_value_surface, justify='center')
box.bind("&lt;&lt;ComboboxSelected&gt;&gt;", new_selection_surface)
box['values'] = surface_types
box.current()
box.grid(column=2, row=1, pady=10, padx=15)


def surface():
    if 'ATP Hard Court' in box_value_surface.get():
        return 'match_stats_atp_.csv'
    else:
        if 'ATP Clay Court' in box_value_surface.get():
            return 'match_stats_atp_1.csv'
        else:
            if 'ATP Grass Court' in box_value_surface.get():
                return 'match_stats_atp_10.csv'

f = open('CSV FILE BASED ON SELECTION 1st DROPDOWN BOX')
csv_f = csv.reader(f)
players_names = []
for row in csv_f:
    players_names.append(row[2])

def new_selection_p1(event):
    return player1()

box_value_p1 = StringVar()
box = ttk.Combobox(frame, textvariable=box_value_p1, justify='center')
box.bind("&lt;&lt;ComboboxSelected&gt;&gt;", new_selection_p1)
box['values'] = players_names
box.current()
box.grid(column=2, row=2, pady=10, padx=15)


def player1():
    with open('CSV FILE BASED ON SELECTION 1st DROPDOWN BOX') as csvfile:
        read_csv = csv.reader(csvfile, delimiter=',')
        service_points_wins = []
        return_points_wins = []
        names = []
        for row in read_csv:
            name = row[2]
            services_point = row[10]
            returns_point = row[4]
            service_points_wins.append(services_point)
            return_points_wins.append(returns_point)
            names.append(name)
        what_name = (box_value_p1.get())
        name_dex = names.index(what_name)
        service_points_wins = service_points_wins[name_dex]
        points_services_point = return_points_wins[name_dex]
        v1player1.set(service_points_wins.replace("%", ''))
        v2player1.set(points_services_point.replace("%", ''))


run = ttk.Button(content, text='Run')
run.grid(column=4, row=3)
cancel = ttk.Button(content, text="Cancel", command=master.destroy)
cancel.grid(column=5, row=3)

master.columnconfigure(0, weight=1)
master.rowconfigure(0, weight=1)
content.columnconfigure(0, weight=3)
content.columnconfigure(1, weight=3)
content.columnconfigure(2, weight=3)
content.columnconfigure(3, weight=1)
content.columnconfigure(4, weight=1)
content.rowconfigure(1, weight=1)

master.geometry("1000x500+100+100")
master.mainloop()
</code></pre>

<p>It is important to understand what your code does. What you were trying to do is open a file at the time of the start of your program while the filename can only be known, after some time when the user has selected an option.
Therefore you need to make sure that the <code>file.open()</code> is only executed when the filename is known. That means that it should happen only inside the function <code>func</code> that you bind to the combobox via <code>box1.bind("&lt;&lt;ComboboxSelected&gt;&gt;", func)</code></p>

<p>Inside this function you can simply get the current selection of the dropdown and use it for determining the filename. This can be efficiently done with a dictionary.</p>

<p>This is the code that might do the trick for you:</p>

<pre><code>from Tkinter import *
import ttk
import csv



players_names = []
surface_types = ['ATP Hard Court', 'ATP Clay Court', 'ATP Grass Court']
choices = {'ATP Hard Court'  : 'match_stats_atp_.csv'  , 
           'ATP Clay Court'  : 'match_stats_atp_1.csv' ,
           'ATP Grass Court' : 'match_stats_atp_10.csv'}


master = Tk()

content = ttk.Frame(master, padding=(12, 12, 12, 12))
frame = ttk.Frame(content, borderwidth=5, relief="groove", width=300, height=100)
content.grid(column=0, row=0, sticky=(N, S, E, W))
frame.grid(column=0, row=0, columnspan=4, rowspan=2, sticky=(N, S, E, W))
text = Text(content, height=8, width=13)
text.grid(row=0, column=4, columnspan=2, rowspan=2, sticky=(N, S, E, W))

v1player1 = StringVar()
v2player1 = StringVar()

c_player1 = Label(frame, text="Service Points Win %:").grid(row=6, column=1, sticky='w')
cc_player1 = Entry(frame, text="value", textvariable=v1player1, justify='center', width=10).grid(row=6, column=2)
d_player1 = Label(frame, text="Return Points Win %: ").grid(row=7, column=1, sticky='w')
dd_player1 = Entry(frame, text="value", textvariable=v2player1, justify='center', width=10).grid(row=7, column=2)


def surface(event):
    players_names = []
    surface_selection = box_value_surface.get()
    try:
        f = open(choices[surface_selection])
        csv_f = csv.reader(f)
        for row in csv_f:
            players_names.append(row[2])
        f.close()
    except:
        #this except is only to make it work without having the csv files at hand
        for name in ["Henry", "Donovan", "John"]:
            players_names.append(name)        
    box2['values'] = players_names

def player1(event):
    surface_selection = box_value_surface.get()
    with open(choices[surface_selection]) as csvfile:
        read_csv = csv.reader(csvfile, delimiter=',')
        service_points_wins = []
        return_points_wins = []
        names = []
        for row in read_csv:
            name = row[2]
            services_point = row[10]
            returns_point = row[4]
            service_points_wins.append(services_point)
            return_points_wins.append(returns_point)
            names.append(name)
        what_name = (box_value_p1.get())
        name_dex = names.index(what_name)
        service_points_wins = service_points_wins[name_dex]
        points_services_point = return_points_wins[name_dex]
        v1player1.set(service_points_wins.replace("%", ''))
        v2player1.set(points_services_point.replace("%", ''))


box_value_surface = StringVar()
box1 = ttk.Combobox(frame, textvariable=box_value_surface, justify='center')
box1['values'] = surface_types
box1.bind("&lt;&lt;ComboboxSelected&gt;&gt;", surface)
box1.grid(column=2, row=1, pady=10, padx=15)

box_value_p1 = StringVar()
box2 = ttk.Combobox(frame, textvariable=box_value_p1, justify='center')
box2.bind("&lt;&lt;ComboboxSelected&gt;&gt;", player1)
box2['values'] = players_names
box2.grid(column=2, row=2, pady=10, padx=15)


run = ttk.Button(content, text='Run')
run.grid(column=4, row=3)
cancel = ttk.Button(content, text="Cancel", command=master.destroy)
cancel.grid(column=5, row=3)

master.mainloop()
</code></pre>

python csv