Skip to content

Instantly share code, notes, and snippets.

@Yagisanatode
Last active July 15, 2021 11:58
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save Yagisanatode/0d1baad4e3a871587ab1 to your computer and use it in GitHub Desktop.
Save Yagisanatode/0d1baad4e3a871587ab1 to your computer and use it in GitHub Desktop.
Python 3 - Open file dialog window in tkinter with filedialog
#! Python 3.4
"""
Open a file dialog window in tkinter using the filedialog method.
Tkinter has a prebuilt dialog window to access files.
This example is designed to show how you might use a file dialog askopenfilename
and use it in a program.
"""
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
root = Tk( )
#This is where we lauch the file manager bar.
def OpenFile():
name = askopenfilename(initialdir="C:/Users/Batman/Documents/Programming/tkinter/",
filetypes =(("Text File", "*.txt"),("All Files","*.*")),
title = "Choose a file."
)
print (name)
#Using try in case user types in unknown file or closes without choosing a file.
try:
with open(name,'r') as UseFile:
print(UseFile.read())
except:
print("No file exists")
Title = root.title( "File Opener")
label = ttk.Label(root, text ="I'm BATMAN!!!",foreground="red",font=("Helvetica", 16))
label.pack()
#Menu Bar
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
root.mainloop()
'''
RESULTS:
>>>
C:/Users/Scott/Documents/Programming/json/test.txt
"I like to move it, groove it!"
'''
@deb991
Copy link

deb991 commented Sep 20, 2019

Thanks for your help. I was trying to get file name from askopenfile but could not find out any way to do so. After find out your code, I had another issue, related cp1252, but finally solve out the issue.

Thanks a lot.

@anthonyr013
Copy link

thanks :D 👍

@vasiauvi
Copy link

Thanks. I've tried it and worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment