tkFileDialog with tKinter

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Daniel M
    New Member
    • Feb 2012
    • 7

    tkFileDialog with tKinter

    I am trying to make a simple app to select and operate on data. I am using Tkinter to build a GUI with four labels and four buttons, side by side. However, for some reason when I run the script, all the button commands get called, asking the user to select all files upon startup, and then afterwards the buttons do not work. Here's my code:
    ---
    Code:
    import numpy
    import scipy
    
    from Tkinter import *
    import tkFileDialog as tkf
    
    filenames = {}
    
    class App:
        def __init__(self, master):
            
                frame = Frame(master)
                frame.pack()
                
                self.Name0 = Label(frame, text = "Initial Data", width=30).grid(row=0, sticky=W,columnspan=2)
                self.Name1 = Label(frame, text = "After Change #1", width=30).grid(row=1, sticky= W,columnspan=2)
                self.Name2 = Label(frame, text = "After Change #2", width=30).grid(row=2,sticky=W,columnspan=2)
                self.Name3 = Label(frame, text = "Current State", width=30).grid(row=3,sticky=W,columnspan=2)
    
                self.Butt0 = Button(frame, text = "Select", command=tkf.askopenfile()).grid(row=0,column=2)
                self.Butt1 = Button(frame, text = "Select", command=tkf.askopenfile()).grid(row=1,column=2)
                self.Butt2 = Button(frame, text = "Select", command=tkf.askopenfile()).grid(row=2,column=2)
                self.Butt3 = Button(frame, text = "Select", command=tkf.askopenfile()).grid(row=3,column=2)
                
        def openfile(self,n):
            print "Okay"
            #More will go here
    
    
    root = Tk()
    
    app = App(root)
    
    root.mainloop()
    ----

    The funny things is that if I remove the dependence on n from the "openfile" method, it works. But obviously, I want to import four distinct sets of data, so I need the dependence on n. This makes no sense! Please help.
    Last edited by bvdet; Feb 15 '12, 07:14 PM. Reason: Ad code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Your button "commands" are being executed as the code is interpreted. "command" needs to be set to a function, not what a function returns. I might initialize 4 attributes to contain the file names and assign "command" similar to this:
    Code:
                self.Butt0 = Button(frame, text = "Select", command=lambda: self.ask_file_name(self.fn1)).grid(row=0,column=2)
    You would need a method "ask_file_n ame" that would accept the variable for assignment of the file name.

    Comment

    Working...