【问题标题】:Browse for file path in python在python中浏览文件路径
【发布时间】:2013-11-25 12:27:19
【问题描述】:

我正在尝试创建一个带有浏览窗口的 GUI 来定位特定文件。 我之前发现了这个问题:Browsing file or directory Dialog in Python

虽然当我查找这些术语时,它似乎并不是我想要的。

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

有人有这方面的资源吗?

编辑:好的,问题已得到解答。对于任何有类似问题的人,请进行研究,那里的代码确实有效。不要在 cygwin 中测试它。由于某种原因,它在那里不起作用。

【问题讨论】:

    标签: python python-2.7 csv tkinter file-io


    【解决方案1】:

    我认为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
    

    编辑:this link 有更多示例

    【讨论】:

    • 太棒了!谢谢!注意任何发现这个的人,不要在 cygwin 中测试它!你会得到一些 $DISPLAY 环境变量错误。它的 cygwins 错误,而不是代码。
    • 你可能需要一个 X 服务器运行它才能在 cygwin 中工作。
    • 我收到错误 ModuleNotFoundError: No module named 'tkFileDialog'。 python 3.7中不再包含这个函数了吗?
    • @SMPerron 在 Python 3.x 中使用 import tkinter.filedialog as fd 或类似的东西。我相信您知道导入的工作原理。
    【解决方案2】:

    这将生成一个只有一个名为“浏览”按钮的 GUI,它会打印出您从浏览器中选择的文件路径。可以通过更改代码段 来指定文件的类型。

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

    【讨论】:

      【解决方案3】:

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

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

      main_win.sourceFolder
      

      【讨论】:

        【解决方案4】:

        我重新编写了 Roberto's 代码,但用 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】:

          基于之前的答案和在此线程中找到的答案:How to give Tkinter file dialog focus 这是在 Python 3 中拉出文件选择器而不看到修补程序窗口的快速方法,还将浏览窗口拉到屏幕前面

          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 )
          

          【讨论】:

          • 这应该是正确的答案
          【解决方案6】:

          使用文件名:

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

          【讨论】:

            猜你喜欢
            • 2020-12-31
            • 1970-01-01
            • 1970-01-01
            • 2011-03-13
            • 2021-11-28
            • 1970-01-01
            • 2014-09-30
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多