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

12,160

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()
Share:
12,160
Thomas Jensen
Author by

Thomas Jensen

Political scientist trying to learn python and R. My blog: polstat.org/blog

Updated on June 07, 2022

Comments

  • Thomas Jensen
    Thomas Jensen almost 2 years

    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!