Choosing a file in Python with simple Dialog

Posted on

Question :

Choosing a file in Python with simple Dialog

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?

Answer #1:

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


Answered By: Mustafa Zengin

Answer #2:

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

from tkinter.filedialog import askopenfilename
filename = askopenfilename()
Answered By: Etaoin

Answer #3:

With EasyGui:

import easygui

To install:

pip install easygui


import easygui
Answered By: Stefano Palazzo

Answer #4:

In Python 2 use the tkFileDialog module.

import tkFileDialog


In Python 3 use the tkinter.filedialog module.

import tkinter.filedialog

Answered By: jfs

Answer #5:

Another option to consider is 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.

Answered By: Gary Kerr

Answer #6:

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

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.

Answered By: kylejmcintyre

Leave a Reply

Your email address will not be published. Required fields are marked *