4

I'm making a program that you use the askopenname file dialog to select a file, which I then want to save the directory to a string so I can use another function (which I already made) to extract the file to a different location that is predetermined. My button code that opens the file dialog is this:

`a = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))`
Phoenix
  • 365
  • 3
  • 5
  • 12
  • 3
    Good for you. Did you have a question? – MattDMo Dec 22 '13 at 00:49
  • What? How did I do that?! My other two questions were fine. – Phoenix Dec 22 '13 at 01:00
  • Can you show us what you've tried? There are plenty of examples in official documentation and on other sites. Show us what you've tried and we can help you understand why your code failed. – Bryan Oakley Dec 22 '13 at 01:03
  • I am not sure how to try right now. That's why I'm asking. – Phoenix Dec 22 '13 at 01:04
  • [Edit](http://stackoverflow.com/posts/20725056/edit) your question to actually ask your question. Include what you've tried and any results. – MattDMo Dec 22 '13 at 01:04
  • When I go to edit the question it shows up as what I typed in the answer. Not sure because I clicked the "ask a question button" So I'm not sure how to fix it. I added my button code I'm using to the question/answer. – Phoenix Dec 22 '13 at 01:13
  • @Phoenix - Are you saying you want to 1) have the user pick a file and 2) get the directory that the chosen file is in? –  Dec 22 '13 at 02:03
  • Yes indeed. Then with that directory I want to extract the files inside. – Phoenix Dec 22 '13 at 02:05

2 Answers2

7

This should be what you want:

import tkinter
import tkinter.filedialog
import getpass
# Need this for the `os.path.split` function
import os
gui = 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()
  • 1
    Isn't there a convenient widget for that? Like `tix.FileEntry(self, dialogtype='tixDirSelectDialog')` but without tix? – pihentagy Mar 31 '14 at 08:52
3

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 tkinter
import tkinter.filedialog
import getpass
from tkFileDialog  import askdirectory
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
    directory= askdirectory()
    print (directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()
Mac
  • 43
  • 7