如何使用Tkinter文件对话框获取路径?

时间:2019-07-17 06:57:12

标签: python tkinter

我需要在Filedialog tkinter中获取选定的路径,但我不知道如何做,因为在图形窗口中直接选择路径时,保存是因为无法提取路径将其存储在变量中

from tkinter import filedialog
open_f = filedialog.asksaveasfile(mode='w', defaultextension='.txt')
path_f = 

如您所见,我需要将在open_f中获得的路由存储在变量path_f ..中,但是open_f仅返回_io.textiowrapper ..

如何在文件对话框中获取路径?

4 个答案:

答案 0 :(得分:1)

如果实际上只需要一个文件名,请使用tkinter.filedialog.asksaveasfilename()

from tkinter import filedialog

filepath = filedialog.asksaveasfilename()
print(filepath)
# '/home/norok2/.xsession-errors'

答案 1 :(得分:0)

您应该使用对象的name方法。如下所示:

open_f = tkFileDialog.asksaveasfile(mode='w', defaultextension='.txt')
path_f = your_file.name

答案 2 :(得分:0)

尝试:

def open():
    open_f = filedialog.asksaveasfile(mode='w', defaultextension='.txt')
    path_f = open_f.name
    # You Can Do Anything Here(e.g. print(path_f))

完整代码:

from tkinter import filedialog

def open():
    open_f = filedialog.asksaveasfile(mode='w', defaultextension='.txt')
    path_f = open_f.name
    print(path_f)
# '/home/norok2/.xsession-errors'

# You can run it by typing:
open()

答案 3 :(得分:0)

out = filedialog.asksaveasfile(mode='w', defaultextension=".xlsx")
out.close()

restr = str(out)
    
RegexPrep = restr.replace("'w'", '')
outRegex = re.findall(r"'(.*?)'", RegexPrep)
ToExcelRegex = str(outRegex)
    
MorePrep = ToExcelRegex.replace("[",'')
MorePrep = MorePrep.replace("]",'')
MorePrep = MorePrep.replace("'",'')
MorePrep = MorePrep.replace(", cp1252",'')
Final = MorePrep.strip()

一种更简单的方法:

open_f = tkFileDialog.asksaveasfile(mode='w', defaultextension='.txt')
path_f = your_file.name