将目录名传递给askopenfilename

时间:2014-08-13 18:16:02

标签: python user-interface tkinter

我有三个功能;使用dirBut,用户选择其输出进入dirname的目录并更新Entry框。在第三个函数dataInput中,用户选择一个文件。我希望打开文件对话框在用户先前选择并由dirname定义的目录中打开,但是,我不确定如何将dirname传递给句柄以便我可以使用它位于askopenfilename,因为askdirectory是从按钮调用的。

def UserFileInput(self,status,name):
    row = self.row
    optionLabel = tk.Label(self)
    optionLabel.grid(row=row, column=0, sticky='w')
    optionLabel["text"] = name
    text = status
    var = tk.StringVar(root)
    var.set(text)
    w = tk.Entry(self, textvariable= var)
    w.grid(row=row, column=1, sticky='ew')
    self.row += 1

    return w, var


def askdirectory(self):
    dirname = tkFileDialog.askdirectory()
    if dirname:
      self.directoryEntry.delete(0, tk.END)
      self.directoryEntry.insert(0, dirname)


def askfilename(self):
  filename = tkFileDialog.askopenfilename(initialdir=dirname)
  if filename:
    self.dataInput.delete(0, tk.END)
    self.dataInput.insert(0, filename)

currentDirectory = os.getcwd()
directory,var = self.UserFileInput(currentDirectory, "Directory")
self.directoryEntry = directory

dirBut = tk.Button(self, text='Select directory...', command = self.askdirectory)
dirBut.grid(row=self.row-1, column=2)

dataInput, var = self.UserFileInput("", "Data input")
self.dataInput = dataInput

fileBut = tk.Button(self, text='Select input file...', command = self.askfilename)
fileBut.grid(row=self.row-1, column=2)

1 个答案:

答案 0 :(得分:4)

假设askdirectoryaskfilename属于同一个类,请尝试将目录指定为self.dirname而不是dirname。然后变量将在类中的任何位置可见。

def askdirectory(self):
    self.dirname = tkFileDialog.askdirectory()
    if self.dirname:
      self.directoryEntry.delete(0, tk.END)
      self.directoryEntry.insert(0, self.dirname)


def askfilename(self):
  filename = tkFileDialog.askopenfilename(initialdir=self.dirname)
  if filename:
    self.dataInput.delete(0, tk.END)
    self.dataInput.insert(0, filename)