Consider:
from tkinter import *
from tkinter import filedialog
def openFile():
filepath = filedialog.askopenfile()
file = open(filepath), 'r')
print(file.read())
file.close()
window = Tk()
button = Button(text="Open",command=openFile)
button.pack()
window.mainloop()
Error:
C:\Users\Hp\PycharmProjects\pythonProject\venv\Scripts\python.exe "C:\Users\Hp\PycharmProjects\pythonProject\open a file.py" File "C:\Users\Hp\PycharmProjects\pythonProject\open a file.py", line 7 file = open(filepath), 'r') ^ SyntaxError: unmatched ')'
Process finished with exit code 1
From the documentation of tkinter.filedialog.askopenfile
:
...create an Open dialog and return the opened file object(s) in read-only mode.
So what filedialog.askopenfile()
returns isn't a file path (you'd use askopenfilename
for that), but the file object you can read from:
def openFile():
file = filedialog.askopenfile()
print(file.read())
file.close()