0

I'm trying to open a .txt file with Python. I'm trying to fill a Tkinter text widget with the files contents.

However with the following snippet, when I try to open the files contents and put it in a the text widget self.Te, nothing happens. Any clues?

Snippet:

    self.Open = tkFileDialog.askopenfilename(initialdir='C:')

    text_file = open(self.Open, "r")
    # self.Te is a text widget
    self.Te.insert('1.0', text_file.read())

1 Answer 1

3

Here is a working example:

#!/usr/bin/env python

from Tkinter import *
from tkFileDialog  import askopenfilename   

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.button = Button(frame, text="QUIT", command=frame.quit)
        self.button.pack(side=BOTTOM)

        self.text = Text(frame)
        self.text.pack(side=TOP)

        self.choosen = askopenfilename(initialdir='~')
        self.text.insert(END, open(self.choosen).read())        

root = Tk()
app = App(root)
root.mainloop()

See also Text widget method documentation:

... Insert text at the given position (typically INSERT or END) ...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.