以askopenfilename选择的字符串获取文件目录 [英] Get a file's directory in a string selected by askopenfilename
本文介绍了以askopenfilename选择的字符串获取文件目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作一个程序,您可以使用askopenname文件对话框选择一个文件,然后将其保存到字符串中,以便可以使用另一个函数(已经完成)将文件提取到一个文件中.预定的其他位置. 我打开文件对话框的按钮代码是:
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))`
推荐答案
这应该是您想要的:
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()
这篇关于以askopenfilename选择的字符串获取文件目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文