Thomas Jensen
Thomas Jensen

Reputation: 860

Tkinter Gui to read in csv file and generate buttons based on the entries in the first row

I need to write a gui in Tkinter that can choose a csv file, read it in and generate a sequence of buttons based on the names in the first row of the csv file (later the data in the csv file should be used to run a number of simulations).

So far I have managed to write a Tkinter gui that will read the csv file, but I am stomped as to how I should proceed:

from Tkinter import *
import tkFileDialog
import csv

class Application(Frame):
    def __init__(self, master = None):
        Frame.__init__(self,master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        top = self.winfo_toplevel()
        self.menuBar = Menu(top)
        top["menu"] = self.menuBar
        self.subMenu = Menu(self.menuBar)
        self.menuBar.add_cascade(label = "File", menu = self.subMenu)
        self.subMenu.add_command( label = "Read Data",command = self.readCSV)


    def readCSV(self):
        self.filename = tkFileDialog.askopenfilename()
        f = open(self.filename,"rb")
        read = csv.reader(f, delimiter = ",")

   app = Application()
   app.master.title("test")
   app.mainloop()

Any help is greatly appreciated!

Upvotes: 4

Views: 13309

Answers (1)

Mike Driscoll
Mike Driscoll

Reputation: 33071

Here's one way to do it. I'm not sure how you'd bind to different event handlers, but you should be able to use a lambda method to pass along the button name (assuming it's unique) and handle different actions that way.

from Tkinter import *
import tkFileDialog
import csv

class Application(Frame):
    def __init__(self, master = None):
        Frame.__init__(self,master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        top = self.winfo_toplevel()
        self.menuBar = Menu(top)
        top["menu"] = self.menuBar
        self.subMenu = Menu(self.menuBar)
        self.menuBar.add_cascade(label = "File", menu = self.subMenu)
        self.subMenu.add_command( label = "Read Data",command = self.readCSV)


    def readCSV(self):
        self.filename = tkFileDialog.askopenfilename()
        f = open(self.filename,"rb")
        read = csv.reader(f, delimiter = ",")
        buttons = read.next()
        print
        for btn in buttons:
            new_btn = Button(self, text=btn, command=self.btnClick)
            new_btn.pack()

    def btnClick(self):
        pass

app = Application()
app.master.title("test")
app.mainloop()

Upvotes: 6

Related Questions