Tuesday, October 16, 2018

TkInter Open select file dialog windows from CMD

Are you writting a script for non tech savvy people that will require them to supply some file path like this: C:\Users\PC Name\Desktop\folder1\folder2\folder3\file-name.csv

As you already guess, many non-tech savvy individuals wont be able to type in such kind of file path to use you script. A work around this is to provide a Graphical User Interface (GUI) to the script, where is easier and user friendly to work with.

Here below is a simple solution using default GUI library that comes with python. This script gets an input file from user interactively via GUI, instead of using the CMD. It is written for both python 2 and 3:-

try:
    # for Python2
    from Tkinter import *   ## notice capitalized T in Tkinter
    from tkFileDialog import askopenfilename

    Tk().withdraw()
    polyfile1 = askopenfilename(title="Select original line file:", filetypes = (("comma-separated value (CSV) files","*.csv"),("all files","*.*"))) # show an "Open" dialog box and return the path to the selected file

    # Using the file...
    print ('Do something with the file in Py2', polyfile1)


except ImportError:
    # for Python3
    from tkinter import *   ## notice lowercase 't' in tkinter here
    from tkinter import filedialog

    Tk().withdraw()
    polyfile1 = filedialog.askopenfilename(title="Select original line file:", filetypes = (("CSV files","*.csv"),("all files","*.*"))) # show an "Open" dialog box and return the path to the selected file

    # Using the file...
    print ('Do something with the file in Py3', polyfile1)




Running the script above should open the select file window as seen below.

That is enjoy the script.

No comments:

Post a Comment