0
votes

I am currently creating a Python Tkinter program to edit and create .txt files. In doing so, I have created a file opening system using the File Dialog method and have the user selected path saved as: a file variable. I have looped through the file and added it to the text widget via the insert method. I opened a test .txt file with a 2 line content. It simply says: this is a test file. (New line) it is used for test purposes

The problem is that the text widget appears blank

My code is:

from tkinter import *
from tkinter import FileDialog
master = Tk()

#all other code like filedialog opening code is here

editarea = Text(master,height=10,width=25)
editarea.grid(column=0,row=1)
f = open(file,"r")
for x in f:
    editarea.insert(END,x)

This code is run in Python 3.7

How do I make the Text widget display the contents of the .txt file and can still be edited?

Many Thanks (For the future)

I am aware the code above is a bit vage and won't run but you hopefully get the gist of my problem :)

1
What have you done to debug this? Have you examined the value of x inside of your loop? The code you posted is correct, though it would be more efficient to read the whole file at once instead of line by line. - Bryan Oakley
@BryanOakley As I am sure you can see from my code, I am a beginner to Python, though I have been doing it for a few years now. As you suggested above to read the whole of the file, what code would i use to do this? Many thanks! - SnappyPenguin
You would use editarea.insert("end", f.read()). - Bryan Oakley

1 Answers

0
votes

here is a better solution, whole file at once

with open(file, "r") as txtr:
    data = txtr.read()
editarea.insert(END, data)

this here is line by line

with open(file, "r") as txtr:
    data = txtr.readlines()
for x in data:
    editarea.insert(END, x)

if for some strange reason it didn't work, try this:

for x in range(len(data)):
    editarea.insert(END, data[x])