在Python中浏览文件路径

13
我正在尝试创建一个GUI,其中包含浏览窗口以定位特定文件。 我早些时候找到了这个问题:Python中浏览文件或目录对话框 虽然当我查找这些术语时,它似乎不是我要寻找的东西。
我所需要的只是从Tkinter按钮启动的某些内容,可以从浏览器返回选定文件的路径。
有人有此资源吗?
编辑:好吧,问题已经得到回答。 对于任何有类似问题的人,请做好调研,出现的代码确实有效。不要在cygwin中测试它。由于某种原因,它在那里无法正常工作。
6个回答

22

我认为TkFileDialog对您可能会有所帮助。

import Tkinter
import tkFileDialog
import os

root = Tkinter.Tk()
root.withdraw() #use to hide tkinter window

currdir = os.getcwd()
tempdir = tkFileDialog.askdirectory(parent=root, initialdir=currdir, title='Please select a directory')
if len(tempdir) > 0:
    print "You chose %s" % tempdir

编辑:此链接还有更多的示例。


2
太棒了!谢谢你! 注意,不要在cygwin中测试它!你会得到一些$DISPLAY环境变量错误。这是cygwin的问题,而不是代码的问题。 - Funkyguy
1
你需要在cygwin中运行X服务器才能使其工作。 - Evan
2
我遇到了错误 ModuleNotFoundError: No module named 'tkFileDialog'。这个函数在Python 3.7中不再包含吗? - Kes Perron
3
在Python 3.x中,请使用import tkinter.filedialog as fd或类似的内容。我相信你知道import的工作原理。 - Nummer_42O

10
我重新制作了Roberto的代码,但用Python3进行了重写(只有小改动)。
您可以直接复制粘贴使用这个.py文件进行简单的演示,或者只复制函数“search_for_file_path”(以及相关的导入),将其作为函数放入您的程序中。
import tkinter
from tkinter import filedialog
import os

root = tkinter.Tk()
root.withdraw() #use to hide tkinter window

def search_for_file_path ():
    currdir = os.getcwd()
    tempdir = filedialog.askdirectory(parent=root, initialdir=currdir, title='Please select a directory')
    if len(tempdir) > 0:
        print ("You chose: %s" % tempdir)
    return tempdir


file_path_variable = search_for_file_path()
print ("\nfile_path_variable = ", file_path_variable)

5

在Python 3中,该模块已经被重命名为filedialog。你可以通过askdirectory方法(event)访问文件夹路径。如果你想选择一个文件路径,请使用askopenfilename

import tkinter 
from tkinter import messagebox
from tkinter import filedialog

main_win = tkinter.Tk()
main_win.geometry("1000x500")
main_win.sourceFolder = ''
main_win.sourceFile = ''
def chooseDir():
    main_win.sourceFolder =  filedialog.askdirectory(parent=main_win, initialdir= "/", title='Please select a directory')

b_chooseDir = tkinter.Button(main_win, text = "Chose Folder", width = 20, height = 3, command = chooseDir)
b_chooseDir.place(x = 50,y = 50)
b_chooseDir.width = 100


def chooseFile():
    main_win.sourceFile = filedialog.askopenfilename(parent=main_win, initialdir= "/", title='Please select a directory')

b_chooseFile = tkinter.Button(main_win, text = "Chose File", width = 20, height = 3, command = chooseFile)
b_chooseFile.place(x = 250,y = 50)
b_chooseFile.width = 100

main_win.mainloop()
print(main_win.sourceFolder)
print(main_win.sourceFile )

注意:变量的值即使在关闭main_win后也会保留。但是,您需要将该变量用作main_win的属性。

main_win.sourceFolder

4

这将生成一个仅有一个名为“浏览”的按钮的GUI界面,当你从浏览器中选择文件路径后,它会将其打印出来。文件类型可以通过更改代码段<*.type>来指定。

from Tkinter import * 
import tkFileDialog

import sys
if sys.version_info[0] < 3:
   import Tkinter as Tk
else:
   import tkinter as Tk


def browse_file():

fname = tkFileDialog.askopenfilename(filetypes = (("Template files", "*.type"), ("All files", "*")))
print fname

root = Tk.Tk()
root.wm_title("Browser")
broButton = Tk.Button(master = root, text = 'Browse', width = 6, command=browse_file)
broButton.pack(side=Tk.LEFT, padx = 2, pady=2)

Tk.mainloop()

4

在之前的答案和这个线程中找到的答案(如何让Tkinter文件对话框获得焦点),下面是一种快速在Python 3中打开文件选择器而不看到tinker窗口的方法,并将浏览窗口拉到屏幕前面。

import tkinter
from tkinter import filedialog

#initiate tinker and hide window 
main_win = tkinter.Tk() 
main_win.withdraw()

main_win.overrideredirect(True)
main_win.geometry('0x0+0+0')

main_win.deiconify()
main_win.lift()
main_win.focus_force()

#open file selector 
main_win.sourceFile = filedialog.askopenfilename(parent=main_win, initialdir= "/",
title='Please select a directory')

#close window after selection 
main_win.destroy()

#print path 
print(main_win.sourceFile )

这应该是正确的答案。 - Kyoujin

1
使用文件名:
from tkinter import * 
from tkinter.ttk import *
from tkinter.filedialog import askopenfile 

root = Tk() 
root.geometry('700x600')

def open_file(): 
    file = askopenfile(mode ='r', filetypes =[('Excel Files', '*.xlsx')])
    if file is not None: 
        print(file.name)
     

btn = Button(root, text ='Browse File Directory', command =lambda:open_file())
btn.pack(side = TOP, pady = 10) 

mainloop() 

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