I'm writing a program that just has a browse button to search for a file and then opens the file you select. I know you can use 'askopenfile' but i wanted to get the name first so it could be displayed in an Entry box in my tkinter window, then the user press 'Use this file' and it would then open.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
def main():
self = Tk()
F1 = LabelFrame(self, text="Select File")
F1.grid(row=0, column=0, padx=3)
browse = Button(F1, text="Browse...", command=openfile)
browse.grid(row=0, column=2, padx=1, pady=3)
E1 = Entry(F1, text="")
E1.grid(row=0, column=1, sticky="ew")
L1 = Label(F1, text="Filename:")
L1.grid(row=0, column=0, padx=3)
B1 = Button(F1, text="Use This File", command=go)
B1.grid(row=1, column=2, padx=3, pady=3)
B2 = Button(F1, text="Cancel", width=7)
B2.grid(row=1, column=1, sticky="e")
self.mainloop()
def openfile():
global filename
filename = filedialog.askopenfilename()
E1.delete(0, END)
E1.insert(0, filename)
def go():
global filename
file = open(filename)
file.read()
print(file)
file.close()
main()
So it makes a tkinter window, you press browse, select a text file, the path is written into the Entry, and then I want to press B1 and get the program to open the file and print the contents, but it just prints:
<_io.TextIOWrapper name='C:/Users/Me/text.txt' mode='r' encoding='cp1252'>