以askopenfilename选择的字符串获取文件目录

Pho*_*nix 2 python filedialog tkinter extract

我正在编写一个程序,您使用askopenname文件对话框选择一个文件,然后将其保存到字符串中,以便可以使用另一个函数(已经完成)将文件提取到另一个位置,是预定的。我打开文件对话框的按钮代码是这样的:

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

iCo*_*dez 5

这应该是您想要的:

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()
Run Code Online (Sandbox Code Playgroud)