通过askopenfilename选择的文件路径如何以字符串形式获取其所在目录?

4

我正在制作一个程序,使用askopenname文件对话框来选择文件,然后我想将目录保存到一个字符串中,以便我可以使用另一个预先设定的函数(我已经创建了)将文件提取到不同的位置。

打开文件对话框的按钮代码如下:

`a = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))`

3
好的。你有问题吗? - MattDMo
什么?我怎么做到的?!我其他两个问题没问题啊。 - Phoenix
你能展示一下你尝试过的内容吗?官方文档和其他网站上有很多例子。展示一下你尝试过的,我们可以帮助你理解为什么你的代码失败了。 - Bryan Oakley
我现在不确定该如何尝试,这就是为什么我在问的原因。 - Phoenix
当我去编辑问题时,它显示为我在答案中键入的内容。不确定是因为我点击了“提问”按钮,所以我不知道该如何修复它。我已经将我正在使用的按钮代码添加到了问题/答案中。 - Phoenix
显示剩余3条评论
2个回答

7
这应该是您想要的内容:
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
有没有很方便的窗口小部件可以做到这一点?就像tix.FileEntry(self, dialogtype='tixDirSelectDialog')一样,但没有使用tix库? - pihentagy

3
如果您知道文件实际所在位置,可以使用以下方式请求目录而不是文件:
from tkFileDialog  import askdirectory  
directory= askdirectory()

然后在代码中:

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

我已经寻找解决方案很久了。谢谢! - Eshita Shukla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接