在编辑器中打开文件时遵循顺序

Revered Order When Open a File in the Editor

所以我正在用 Python Tkinter 制作一个 简单的文本编辑器 。在顶部有 2 个按钮:“保存”和“打开”。(它们显示 open/save 作为对话 windows)。使用保存按钮没问题,但是当我想在我的编辑器中打开一个文件时,它显示逆序

这是我的代码:

from tkinter import *
from tkinter import filedialog

window = Tk()

window.geometry("1600x900")

window.title("Text Editor")

def save():

    editor_content = editor.get("1.0", END)

    saving = filedialog.asksaveasfile(mode = "w", defaultextension = ".py")

    saving.write(editor_content)

    saving.close()

def open():
    open_file = filedialog.askopenfile(initialdir="/", title="Open File", filetypes=(("Python files", ".py"), ("Text Files", ".txt"), ("All Files", "*.*")))

    for file_opened in open_file:
            editor.insert(0.0, f'{file_opened}')

editor = Text(bg = "#1f1f1f", fg = "#b5b5b5", width = 105, height = 25,wrap = WORD, padx = 10, pady = 10, font = "consolas, 20")
editor.place(x = 0, y = 40)

save_btn = Button(width = 10, height = 2, bg = "#5e5e5e", relief = "flat", text = "Save", fg = "white", activebackground = "#4e4e4e", activeforeground = "white", command = save)
save_btn.place(x = 0, y = 0)

open_btn = Button(width = 10, height = 2, bg = "#5e5e5e", relief = "flat", text = "Open", fg = "white", activebackground = "#4e4e4e", activeforeground = "white", command = open)
open_btn.place(x = 80, y = 0)

window.mainloop()

你的问题很容易解决,问题出在以下部分代码

for file_opened in open_file:
    editor.insert(0.0, f'{file_opened}')

如您所见,您将文件的每一行插入到 0.0 索引 (0 行 . 0 列),这意味着它将在前一行之上添加下一行line 您所要做的就是在上一行之后添加该行。这可以通过将索引值更改为 "end" 而不是 0.0.

来完成
for file_opened in open_file:
    editor.insert('end', f'{file_opened}')

就像下面提到的 ,如果您只想将整个文件一次插入到 Text 小部件中,那么您可以执行以下操作。

editor.insert('end', open_file.read())