使用简单的对话框在 Python 中选择文件

发布于 2024-09-16 14:44:19 字数 113 浏览 14 评论 0原文

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

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

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

I would like to get file path as input in my Python console application.

Currently I can only ask for full path as an input in the console.

Is there a way to trigger a simple user interface where users can select file instead of typing the full path?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

终止放荡 2024-09-23 14:44:19

使用 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)

完毕!

How about using 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)

Done!

泅渡 2024-09-23 14:44:19

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

from tkinter.filedialog import askopenfilename
filename = askopenfilename()

Python 3.x version of Etaoin's answer for completeness:

from tkinter.filedialog import askopenfilename
filename = askopenfilename()
源来凯始玺欢你 2024-09-23 14:44:19

使用 EasyGui

import easygui
print(easygui.fileopenbox())

安装:

pip install easygui

演示:

import easygui
easygui.egdemo()

With EasyGui:

import easygui
print(easygui.fileopenbox())

To install:

pip install easygui

Demo:

import easygui
easygui.egdemo()
回忆那么伤 2024-09-23 14:44:19

在 Python 2 中使用 tkFileDialog 模块。

import tkFileDialog

tkFileDialog.askopenfilename()

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

import tkinter.filedialog

tkinter.filedialog.askopenfilename()

In Python 2 use the tkFileDialog module.

import tkFileDialog

tkFileDialog.askopenfilename()

In Python 3 use the tkinter.filedialog module.

import tkinter.filedialog

tkinter.filedialog.askopenfilename()
弥繁 2024-09-23 14:44:19

这对我有用

参考: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)

This worked for me

Reference : 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)
不再见 2024-09-23 14:44:19

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

下面的两个片段返回“打开”或“另存为”中的文件路径(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'

The suggested root.withdraw() (also here) hides the window instead of deleting it, and was causing problems when using interactive console in VS Code ("duplicate execution" error).

Below two snippets to return the file path in "Open" or "Save As" (python 3 on Windows):

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'
浅黛梨妆こ 2024-09-23 14:44:19

另一个值得考虑的选择是 Zenity:http://freecode.com/projects/zenity

我遇到过这样的情况:我正在开发一个 Python 服务器应用程序(没有 GUI 组件),因此不想引入对任何 python GUI 工具包的依赖,但我希望我的一些调试脚本由输入文件参数化,并且想要如果用户未在命令行上指定文件,则以可视方式提示用户输入文件。 Zenity 是一个完美的选择。为此,请使用子进程模块调用“zenity --file-selection”并捕获标准输出。当然,这个解决方案不是特定于 Python 的。

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

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

流绪微梦 2024-09-23 14:44:19

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

https://stackoverflow.com/a/9319832

wxPython 版本生成的文件对话框与我在 xfce 桌面上安装的 OpenSUSE Tumbleweed 上的几乎任何其他应用程序的打开文件对话框看起来相同,而 tkinter 则生成了一些局促且难以通过不熟悉的方式阅读的内容 -滚动界面。

I obtained much better results with wxPython than tkinter, as suggested in this answer to a later duplicate question:

https://stackoverflow.com/a/9319832

The wxPython version produced the file dialog that looked the same as the open file dialog from just about any other application on my OpenSUSE Tumbleweed installation with the xfce desktop, whereas tkinter produced something cramped and hard to read with an unfamiliar side-scrolling interface.

掌心的温暖 2024-09-23 14:44:19

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

import plyer

plyer.filechooser.open_file()

还有其他两种方法,choose_dirsave_file。请参阅此处文档中的详细信息。

Using Plyer you can get a native file picker on Windows, macOS, Linux, and even Android.

import plyer

plyer.filechooser.open_file()

There are two other methods, choose_dir and save_file. See details in the docs here.

温馨耳语 2024-09-23 14:44:19

这是一个简单的函数,可以在终端窗口中显示文件选择器。
该方法支持选择多个文件或目录。这具有即使在不支持 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 安装查询

Here is a simple function to show a file chooser right in the terminal window.
This method supports selecting multiple files or directories. This has the added benefit of running even in an environment where GUI is not supported.

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)

To install enquiers do,

pip install enquiries

七度光 2024-09-23 14:44:19

我解决了所有相关问题
from tkinter import * from tkinter import filedialog

只需从 pycharm IDE 迁移到 Visual Studio Code IDE,所有问题都得到解决。

I resolved all problem related to
from tkinter import * from tkinter import filedialog

by just migrating from pycharm IDE to visual studio code IDE and every problem is solved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文