在python中浏览文件路径

Fun*_*guy 6 python csv file-io tkinter python-2.7

我正在尝试使用浏览窗口创建GUI以查找特定文件.我之前发现了这个问题:在Python中浏览文件或目录Dialog

虽然当我查看条款时,它似乎并不是我想要的.

我需要的只是可以从Tkinter按钮启动的东西,它从浏览器返回所选文件的路径.

有人有资源吗?

编辑:好的,所以问题已得到解答.对于任何有类似问题的人,做你的研究,那里的代码都可以.不要在cygwin中测试它.由于某种原因它在那里不起作用.

Rob*_*rto 10

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

编辑:这个链接有更多的例子

  • @SMPerron在Python 3.x中使用 ```import tkinter.filedialog as fd``` 或类似的东西。我相信您知道导入是如何工作的。 (3认同)
  • 惊人的!谢谢!请注意发现此问题的任何人,不要在 cygwin 中对其进行测试!你会得到一些 $DISPLAY 环境变量错误。它的 cygwins 错误,而不是代码。 (2认同)
  • 我收到错误“ModuleNotFoundError:没有名为“tkFileDialog”的模块”。python 3.7中不再包含这个函数了吗? (2认同)

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


Afs*_*iri 5

在 python 3 中,它已重命名为 filedialog。您可以通过askdirectory方法(事件)访问文件夹,如下所示。如果您想选择文件路径,请使用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 )
Run Code Online (Sandbox Code Playgroud)

注意:即使关闭 main_win 后变量的值仍然存在。但是,您需要使用该变量作为 main_win 的属性,即

main_win.sourceFolder
Run Code Online (Sandbox Code Playgroud)