Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

python - 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...