How can I use the output from tkFileDialog.askdirectory to populate the tkinter input field

I have a tkinter input field in which the user can insert the directory path. Alternatively, the user can click a button to select a directory. How can I set the exit from the button to fill in the input field? I tried the following but is dirnamenot a global variable and therefore not recognized UserFileInput. Also how can I link the button next to the input 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()
+4
source share
1 answer

UserFileInput var, w. var.set(dirname) askdirectory, .

, text = str(dirname) if dirname else status. text = status, dirname ?

: , . " " , , , , .

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()
+7

All Articles