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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With