- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
askopenfile() function in Python Tkinter
Instead of hard coding the path to a file to be used by a python program, we can allow the user to browse the os folder structure using a GUI and let the user select the file. This is achieved using the tkinter module in which we define a canvas and put a button on it to browse the files.
In the below program, we define a file opener function. We only use this function to open a text file as python can read the content of a text file and print it out in a much readable manner. We can read any text based files like .txt or .csv files.
from tkinter import * from tkinter import filedialog base = Tk() # Create a canvas base.geometry('150x150') # Function for opening the file def file_opener(): input = filedialog.askopenfile(initialdir="/") print(input) for i in input: print(i) # Button label x = Button(base, text ='Select a .txt/.csv file', command = lambda:file_opener()) x.pack() mainloop()
The below dialogue box opens to browse a file.
Then we choose a file.
Running the above code gives us the following result −
<_io.TextIOWrapper name='C:/Users/Pradeep/Documents/welcome.txt' mode='r' encoding='cp1252'> Hello There ! Welcome to Tutorialspoint!
- Binding function in Python Tkinter
- asksaveasfile() function in Python Tkinter
- Tkinter Programming in Python
- Function to close the window in Tkinter
- How to return a JSON object from a Python function in Tkinter?
- How to stop Tkinter after function?
- destroy() method in Tkinter - Python
- Different messages in Tkinter - Python
- Python - geometry method in Tkinter
- after method in Python Tkinter
- Collapsible Pane in Tkinter Python
- Progressbar widget in Python Tkinter
- Mouse Position in Python Tkinter
- Develop Notepad using Tkinter in python
- Color game using Tkinter in Python