1

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'>
nbro
  • 15,395
  • 32
  • 113
  • 196

2 Answers2

4

You need to save the returned value from read() into a variable and print that, not the file object.

file_content = file.read()
print(file_content)
Novel
  • 13,406
  • 2
  • 25
  • 41
0

I know this is an old question and by now OP probably figured it out already but just to add, you cant use local variables from one class to another without declaring them global, so even if you do what Novel said and change the "go" class you'll still have issues printing the files.

what you must do is inside the main() class declare the E1 variable as global, and also (in case you're using this code for something else) do the same for others:

global E1, L1, B1, B2

This should be inside main()