[英]displaying file name, not content in text widget tkinter Python
[英]Python Tkinter Text Widget not displaying contents from .txt file
我目前正在創建一個 Python Tkinter 程序來編輯和創建.txt 文件。 為此,我使用文件對話框方法創建了一個文件打開系統,並將用戶選擇的路徑保存為:文件變量。 我已經遍歷文件並通過 insert 方法將其添加到文本小部件中。 我打開了一個包含 2 行內容的 test.txt 文件。 它只是說:這是一個測試文件。 (新行)它用於測試目的
問題是文本小部件顯示為空白
我的代碼是:
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)
此代碼在 Python 3.7 中運行
如何使文本小部件顯示 .txt 文件的內容並且仍然可以編輯?
非常感謝(未來)
我知道上面的代碼有點模糊,不會運行,但你希望能明白我的問題的要點:)
這是一個更好的解決方案,一次整個文件
with open(file, "r") as txtr:
data = txtr.read()
editarea.insert(END, data)
這是一行一行的
with open(file, "r") as txtr:
data = txtr.readlines()
for x in data:
editarea.insert(END, x)
如果由於某種奇怪的原因它不起作用,試試這個:
for x in range(len(data)):
editarea.insert(END, data[x])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.