Monday 18 May 2015

Python 3 - Open File Dialog Window In Tkinter With filedialog

I wanted to make a file loader for a chatbot program I am working on in Python 3 using Tkinter. I thought  that it would be a tricky task until I stumbled up the filedialoge module and the askopenfilename function.

Tkinter uses the filedialoge access the askopenfilename to open a window that matches the format of your operating system. Mine is currently Windows 8, so it looks like this.


How good does that look. To use the askopenfilename function you need to import it:
from tkinter.filedialog import askopenfilename
Because you will probably want to run the file from a command in a menu bar of from a button click it's probably a good idea to wrap it in a function:
def OpenFile():
    name = askopenfilename(initialdir="C:/Users/Batman/tkinter/",
                           filetypes =(("Text File", "*.txt"),("All Files","*.*")),
                           title = "Choose a file."
                           )
The askopenfilename function can have a number of options or no options and you can leave it blank. The ones I have used in this example I think are the most useful:

initialdir 

 set the the initial file location that the function will open it.

filetypes


This allows you set the type of files you want the user open. The end result appears in the bottom drop down menu.
First you set the file in a tuple ("Text File", "*.txt"). The first input is the title you want to name the file type(e.g. "Text File") and the second string is the file name ("*.txt"). If you have a custom file type, like ("*.noob"), then you can use that too.
What I discovered is that it requires a minimum of two file types for this option to work. So if you get an error this might be it.

title

This is the title you want to add to the top bar. 


In the below example you can execute the file in the Menu in File-Open. I thought I'd give you a realistic application of the askopenfilename.
As you can see from the first print the file does not open the document, rather it gets the file location and from there you can open and use the file. In the above example I have opened the file as a variable and then read it because I had a text file. You could as easily put the variable in a label or text widget in tkinter.

Useful Links:
http://effbot.org/tkinterbook/tkinter-file-dialogs.htm
http://tkinter.unpythonic.net/wiki/tkFileDialog

1 comment: