根据选择加载csv文件

时间:2016-09-27 09:20:37

标签: python csv

在我提出问题之前,我已经到处寻找并试图找到解决方案,但找不到解决方案。

我在Tkinter中构建了一个简单的GUI。目标是首先根据下拉框中的选择进行选择。 在我的例子中,主题是"网球"。

我的目标是用户可以先选择" surface"在网球比赛上进行的比赛。我们有3个选择。 Hard Court,Clay Court或Grass Court。

基于所做的选择,我想要加载不同的csv文件。

  • Hard Court文件名为" match_stats_atp_.csv"
  • Clay Court文件名为" match_stats_atp_1.csv"
  • Grass Court文件名为" match_stats_atp_10.csv"

每个csv文件都根据特定的网球表面保存数据。

我现在的问题是,如何根据第一个下拉框中的选择加载csv文件? csv文件与我的脚本位于同一目录中。

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("<<ComboboxSelected>>", 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("<<ComboboxSelected>>", 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()

1 个答案:

答案 0 :(得分:0)

了解代码的作用非常重要。您尝试做的是在程序启动时打开文件,而文件名只能在用户选择了一个选项后的某个时间才知道。 因此,您需要确保仅在知道文件名时才执行file.open()。这意味着它应该仅在通过func

绑定到组合框的函数box1.bind("<<ComboboxSelected>>", func)内发生

在此功能中,您只需获取当前选择的下拉列表并使用它来确定文件名。这可以通过字典有效地完成。

这是可能为您解决问题的代码:

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("<<ComboboxSelected>>", 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("<<ComboboxSelected>>", 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()