Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the output from tkFileDialog.askdirectory to fill a tkinter Entry box

I have a tkinter Entry box in which the user can insert a path to the directory. Alternatively the user can click a button to select the directory. How can I set the output from the button to fill the Entry box? I have tried the following but dirname is not a global variable and so is not recognised by UserFileInput. Also how can I bind the button next to the entry field.

from Tkinter import *
import tkFileDialog

def askdirectory():
  dirname = tkFileDialog.askdirectory()
  return dirname

def UserFileInput(status,name):
  optionFrame = Frame(root)
  optionLabel = Label(optionFrame)
  optionLabel["text"] = name
  optionLabel.pack(side=LEFT)
  text = str(dirname) if dirname else status
  var = StringVar(root)
  var.set(text)
  w = Entry(optionFrame, textvariable= var)
  w.pack(side = LEFT)
  optionFrame.pack()
  return w


if __name__ == '__main__':
  root = Tk()


  dirBut = Button(root, text='askdirectory', command = askdirectory)
  dirBut.pack(side = RIGHT)

  directory = UserFileInput("", "Directory")


  root.mainloop()
like image 763
218 Avatar asked Aug 13 '14 09:08

218


1 Answers

Your UserFileInput should return var, not w. Then you can use var.set(dirname) in your askdirectory function which doesn't have to return anything.

I'm not sure however what you try to achieve with text = str(dirname) if dirname else status. Why not just use text = status since dirname can't yet be defined there?

Edit: This should work the way you want it to. The 'print entry text' button shows that you can retreive whatever is in the entry box, either written by the user or put there by the code.

from Tkinter import *
import tkFileDialog

def askdirectory():
  dirname = tkFileDialog.askdirectory()
  if dirname:
    var.set(dirname)

def UserFileInput(status,name):
  optionFrame = Frame(root)
  optionLabel = Label(optionFrame)
  optionLabel["text"] = name
  optionLabel.pack(side=LEFT)
  text = status
  var = StringVar(root)
  var.set(text)
  w = Entry(optionFrame, textvariable= var)
  w.pack(side = LEFT)
  optionFrame.pack()
  return w, var

def Print_entry():
  print var.get()

if __name__ == '__main__':
  root = Tk()

  dirBut = Button(root, text='askdirectory', command = askdirectory)
  dirBut.pack(side = RIGHT)
  getBut = Button(root, text='print entry text', command = Print_entry)
  getBut.pack(side = BOTTOM)

  w, var = UserFileInput("", "Directory")

  root.mainloop()
like image 87
fhdrsdg Avatar answered Oct 06 '22 00:10

fhdrsdg