Get a file's directory in a string selected by askopenfilename
This should be what you want:
import tkinterimport tkinter.filedialogimport getpass# Need this for the `os.path.split` functionimport osgui = tkinter.Tk()user = getpass.getuser()def click(): # Get the file file = tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user) # Split the filepath to get the directory directory = os.path.split(file)[0] print(directory)button = tkinter.Button(gui, command=click)button.grid()gui.mainloop()
If you know where the file actually is, you could always just ask for a directory instead of the file using:
from tkFileDialog import askdirectory directory= askdirectory()
Then in the code:
import tkinterimport tkinter.filedialogimport getpassfrom tkFileDialog import askdirectory# Need this for the `os.path.split` functionimport osgui = tkinter.Tk()user = getpass.getuser()def click(): directory= askdirectory() print (directory)button = tkinter.Button(gui, command=click)button.grid()gui.mainloop()