Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python | asksaveasfile() function in Tkinter
Next article icon

While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help ofopen() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. 
With the help of GUI, you may not require to specify the path of any file but you can directly open a file and read it's content. 

In order to use askopenfile() function you may require to follow these steps:

->import tkinter->from tkinter.filedialog import askopenfile ## Now you can use this function->file = askopenfile(mode='r', filetypes=[('any name you want to display', 'extension of file type')])

We have to specify the mode in which you want to open the file like in above snippet, this will open a file in reading mode. 
 

Python3
# importing tkinter and tkinter.ttk# and all their functions and classesfromtkinterimport*fromtkinter.ttkimport*# importing askopenfile function# from class filedialogfromtkinter.filedialogimportaskopenfileroot=Tk()root.geometry('200x100')# This function will be used to open# file in read mode and only Python files# will be openeddefopen_file():file=askopenfile(mode='r',filetypes=[('Python Files','*.py')])iffileisnotNone:content=file.read()print(content)btn=Button(root,text='Open',command=lambda:open_file())btn.pack(side=TOP,pady=10)mainloop()

Output:

 askopenfile() function in Tkinter 

Printed content of selected file -

 Printed content of selected file 

Comparison of content of original file and printed content - 

Comparison of content of original file and printed contentNote: In above code only .py (python files) types files will be open. To open specified type of files, one has to mention it in thefiletypes option along with it's extension as done in above code.


Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp