Choosing a file in Python with simple Dialog

2019-01-04 06:26发布

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?

5条回答
混吃等死
2楼-- · 2019-01-04 06:46

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

from tkinter.filedialog import askopenfilename
filename = askopenfilename()
查看更多
Melony?
3楼-- · 2019-01-04 06:46

Use the tkFileDialog module which is part of the standard installation.

import tkFileDialog

print tkFileDialog.askopenfilename()
查看更多
Melony?
4楼-- · 2019-01-04 06:55

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.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-04 07:03

With EasyGui (documentation generated by pydoc and epydoc for version 0.96):

import easygui
print easygui.fileopenbox()

To install:

pip install easygui

Demo:

import easygui
easygui.egdemo()
查看更多
虎瘦雄心在
6楼-- · 2019-01-04 07:04

How about using tkinter?

from Tkinter import Tk
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!

查看更多
登录 后发表回答