在Python中快速便捷的文件对话框? [英] Quick and easy file dialog in Python?

查看:89
本文介绍了在Python中快速便捷的文件对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的脚本,可以解析文件并将其内容加载到数据库中.我不需要UI,但是现在我正在提示用户使用raw_input解析文件,这是最不友好的,尤其是因为用户无法复制/粘贴路径.我想要一种快速简便的方法来向用户显示文件选择对话框,他们可以选择文件,然后将其加载到数据库中. (在我的用例中,如果他们碰巧选择了错误的文件,它将导致解析失败,即使将其加载到数据库中也不会有问题.)

I have a simple script which parses a file and loads it's contents to a database. I don't need a UI, but right now I'm prompting the user for the file to parse using raw_input which is most unfriendly, especially because the user can't copy/paste the path. I would like a quick and easy way to present a file selection dialog to the user, they can select the file, and then it's loaded to the database. (In my use case, if they happened to chose the wrong file, it would fail parsing, and wouldn't be a problem even if it was loaded to the database.)

import tkFileDialog
file_path_string = tkFileDialog.askopenfilename()

此代码接近我想要的代码,但它留下了一个令人讨厌的空框架(无法将其关闭,可能是因为我尚未注册close事件处理程序).

This code is close to what I want, but it leaves an annoying empty frame open (which isn't able to be closed, probably because I haven't registered a close event handler).

我不必使用tkInter,但是因为它在Python标准库中,所以它是最快,最简单解决方案的理想选择.

I don't have to use tkInter, but since it's in the Python standard library it's a good candidate for quickest and easiest solution.

在没有任何其他UI的情况下,在脚本中提示文件或文件名的快速简便的方法是什么?

Whats a quick and easy way to prompt for a file or filename in a script without any other UI?

推荐答案

如果您不希望拥有任何其他依赖项,Tkinter是最简单的方法. 要仅显示没有任何其他GUI元素的对话框,您必须使用 withdraw 方法:

Tkinter is the easiest way if you don't want to have any other dependencies. To show only the dialog without any other GUI elements, you have to hide the root window using the withdraw method:

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

Python 2变体:

Python 2 variant:

import Tkinter, tkFileDialog

root = Tkinter.Tk()
root.withdraw()

file_path = tkFileDialog.askopenfilename()

这篇关于在Python中快速便捷的文件对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆