By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,603 Members | 1,053 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,603 IT Pros & Developers. It's quick & easy.

tkFileDialog with tKinter

P: 7
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:
---
Expand|Select|Wrap|Line Numbers
  1. import numpy
  2. import scipy
  3.  
  4. from Tkinter import *
  5. import tkFileDialog as tkf
  6.  
  7. filenames = {}
  8.  
  9. class App:
  10.     def __init__(self, master):
  11.  
  12.             frame = Frame(master)
  13.             frame.pack()
  14.  
  15.             self.Name0 = Label(frame, text = "Initial Data", width=30).grid(row=0, sticky=W,columnspan=2)
  16.             self.Name1 = Label(frame, text = "After Change #1", width=30).grid(row=1, sticky= W,columnspan=2)
  17.             self.Name2 = Label(frame, text = "After Change #2", width=30).grid(row=2,sticky=W,columnspan=2)
  18.             self.Name3 = Label(frame, text = "Current State", width=30).grid(row=3,sticky=W,columnspan=2)
  19.  
  20.             self.Butt0 = Button(frame, text = "Select", command=tkf.askopenfile()).grid(row=0,column=2)
  21.             self.Butt1 = Button(frame, text = "Select", command=tkf.askopenfile()).grid(row=1,column=2)
  22.             self.Butt2 = Button(frame, text = "Select", command=tkf.askopenfile()).grid(row=2,column=2)
  23.             self.Butt3 = Button(frame, text = "Select", command=tkf.askopenfile()).grid(row=3,column=2)
  24.  
  25.     def openfile(self,n):
  26.         print "Okay"
  27.         #More will go here
  28.  
  29.  
  30. root = Tk()
  31.  
  32. app = App(root)
  33.  
  34. 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.
Feb 15 '12 #1
Share this Question
Share on Google+
1 Reply

bvdet
Expert Mod 2.5K+
P: 2,851
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:
Expand|Select|Wrap|Line Numbers
  1.             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_name" that would accept the variable for assignment of the file name.
Feb 15 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.