Get a file's directory in a string selected by askopenfilename

雨燕双飞 提交于 2019-12-02 05:51:36

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/20725056/get-a-files-directory-in-a-string-selected-by-askopenfilename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!