[英]Python Tkinter Text Widget not displaying contents from .txt file
I am currently creating a Python Tkinter program to edit and create.txt files.我目前正在创建一个 Python Tkinter 程序来编辑和创建.txt 文件。 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.我已经遍历文件并通过 insert 方法将其添加到文本小部件中。 I opened a test.txt file with a 2 line content.我打开了一个包含 2 行内容的 test.txt 文件。 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此代码在 Python 3.7 中运行
How do I make the Text widget display the contents of the.txt file and can still be edited?如何使文本小部件显示 .txt 文件的内容并且仍然可以编辑?
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:)我知道上面的代码有点模糊,不会运行,但你希望能明白我的问题的要点:)
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.