【问题标题】:Choosing a file in Python with simple Dialog使用简单的对话框在 Python 中选择文件
【发布时间】:2011-04-04 12:30:05
【问题描述】:

我想在我的 Python 控制台应用程序中获取文件路径作为输入。

目前我只能在控制台中要求完整路径作为输入。

有没有办法触发一个简单的用户界面,用户可以选择文件而不是输入完整路径?

【问题讨论】:

  • 好问题。我只是在找这个。我投了赞成票。谢谢!

标签: python user-interface dialog filechooser


【解决方案1】:

使用 tkinter 怎么样?

from Tkinter import Tk     # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)

完成!

【讨论】:

  • 我得到 TypeError: 'module' object is not callable on Tk().withdraw() - 有什么想法吗?
  • 我必须先做 root = Tk.Tk() 然后 root.withdraw()。现在打开文件对话框窗口并没有关闭。
  • 使用 Python 3.x,我相信“Tkinter”实际上应该是全小写的,“tkinter”。
  • @WestAce 是的,它已从 Python3 的“Tkinter”更改为“tkinter”
  • 有没有办法只允许某些类型的文件?例如。我希望用户只选择图像文件
【解决方案2】:

Etaoin 的 Python 3.x 版本的完整性回答:

from tkinter.filedialog import askopenfilename
filename = askopenfilename()

【讨论】:

  • 对于总并行度,可能还应该有import tkinter + tkinter.Tk().withdraw()
  • 这对我不起作用(在 Mac,Python 3.6.6 上)GUI 窗口打开,但你无法关闭它,你会得到死亡沙滩球
  • 这里也一样。文件对话框不会关闭
  • 此代码与接受的答案完全相同,但不完整。
  • 在 Mac 10.14.6 上,这会打开文件查找器,然后它只会使整个系统崩溃:(
【解决方案3】:

EasyGui:

import easygui
print(easygui.fileopenbox())

安装:

pip install easygui

演示:

import easygui
easygui.egdemo()

【讨论】:

  • 这是迄今为止最好的解决方案。主要原因是easygui是pip包,安装方便
  • 在 Mac OSX 10.14.5、python 3.6.7、easygui 0.98.1 上,当我尝试这个时,我遇到了可怕的崩溃。不推荐。
  • 为什么print easygui.diropenbox() 出现invalid syntax 错误?
  • @ChristopherBarber 与 10.14.6 相同。 Python 只是不断退出。
【解决方案4】:

在 Python 2 中使用 tkFileDialog 模块。

import tkFileDialog

tkFileDialog.askopenfilename()

在 Python 3 中使用 tkinter.filedialog 模块。

import tkinter.filedialog

tkinter.filedialog.askopenfilename()

【讨论】:

  • 它不是 Python 3 标准安装的一部分。
【解决方案5】:

另一个需要考虑的选项是 Zenity:http://freecode.com/projects/zenity

我有一种情况,我正在开发一个 Python 服务器应用程序(没有 GUI 组件),因此不想引入对任何 Python GUI 工具包的依赖,但我希望我的一些调试脚本由输入文件参数化如果他们没有在命令行上指定一个文件,并且想要直观地提示用户输入文件。 Zenity 非常适合。为此,请使用 subprocess 模块调用“zenity --file-selection”并捕获标准输出。当然,这个解决方案不是特定于 Python 的。

Zenity 支持多个平台,并且碰巧已经安装在我们的开发服务器上,因此它有助于我们的调试/开发,而不会引入不需要的依赖项。

【讨论】:

    【解决方案6】:

    这对我有用

    参考:https://www.youtube.com/watch?v=H71ts4XxWYU

    import  tkinter as tk
    from tkinter import filedialog
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename()
    print(file_path)
    

    【讨论】:

      【解决方案7】:

      我使用 wxPython 获得了比 tkinter 更好的结果,正如对稍后重复问题的回答中所建议的那样:

      https://stackoverflow.com/a/9319832

      wxPython 版本生成的文件对话框与我在 xfce 桌面上安装的 OpenSUSE Tumbleweed 上的任何其他应用程序中的打开文件对话框看起来相同,而 tkinter 生成的内容狭窄且难以阅读,带有不熟悉的横向滚动界面。

      【讨论】:

        【解决方案8】:

        这是一个在终端窗口中显示文件选择器的简单函数。 此方法支持选择多个文件或目录。这具有即使在不支持 GUI 的环境中也能运行的额外好处。

        from os.path import join,isdir
        from pathlib import Path
        from enquiries import choose,confirm
        
        def dir_chooser(c_dir=getcwd(),selected_dirs=None,multiple=True) :
            '''
                This function shows a file chooser to select single or
                multiple directories.
            '''
            selected_dirs = selected_dirs if selected_dirs else set([])
        
            dirs = { item for item in listdir(c_dir) if isdir(join(c_dir, item)) }
            dirs = { item for item in dirs if join(c_dir,item) not in selected_dirs and item[0] != "." } # Remove item[0] != "." if you want to show hidde
        
            options = [ "Select This directory" ]
            options.extend(dirs)
            options.append("⬅")
        
            info = f"You have selected : \n {','.join(selected_dirs)} \n" if len(selected_dirs) > 0 else "\n"
            choise = choose(f"{info}You are in {c_dir}", options)
        
            if choise == options[0] :
                selected_dirs.add(c_dir)
        
                if multiple and confirm("Do you want to select more folders?") :
                    return get_folders(Path(c_dir).parent,selected_dirs,multiple)
        
                return selected_dirs
        
            if choise == options[-1] :
                return get_folders(Path(c_dir).parent,selected_dirs,multiple)
        
            return get_folders(join(c_dir,choise),selected_dirs,multiple)
        

        要安装查询器,

        pip 安装查询

        【讨论】:

          【解决方案9】:

          我解决了所有与 from tkinter import * from tkinter import filedialog

          只需从 pycharm IDE 迁移到 visual studio code IDE 即可解决所有问题。

          【讨论】:

            【解决方案10】:

            建议的 root.withdraw()(也称为 here)隐藏窗口而不是删除它,并且在 VS Code 中使用交互式控制台时导致问题(“重复执行”错误)。

            下面两个sn-ps以“打开”或“另存为”(Windows上的python 3)返回文件路径:

            import tkinter as tk
            from tkinter import filedialog
            
            filetypes = (
                ('Text files', '*.TXT'),
                ('All files', '*.*'),
            )
            
            # open-file dialog
            root = tk.Tk()
            filename = tk.filedialog.askopenfilename(
                title='Select a file...',
                filetypes=filetypes,
            )
            root.destroy()
            print(filename)
            
            # save-as dialog
            root = tk.Tk()
            filename = tk.filedialog.asksaveasfilename(
                title='Save as...',
                filetypes=filetypes,
                defaultextension='.txt'
            )
            root.destroy()
            print(filename)
            # filename == 'path/to/myfilename.txt' if you type 'myfilename'
            # filename == 'path/to/myfilename.abc' if you type 'myfilename.abc'
            

            【讨论】:

              【解决方案11】:

              使用Plyer,您可以在 Windows、macOS、Linux 甚至 Android 上获得本机文件选择器。

              import plyer
              
              plyer.filechooser.open_file()
              

              还有另外两种方法,choose_dirsave_file。请参阅文档here 中的详细信息。

              【讨论】:

                猜你喜欢
                • 2017-05-23
                • 1970-01-01
                • 2023-03-29
                • 2020-10-27
                • 1970-01-01
                • 1970-01-01
                • 2011-08-24
                • 1970-01-01
                相关资源
                最近更新 更多