【问题标题】:Revered Order When Open a File in the Editor在编辑器中打开文件时的崇敬顺序
【发布时间】:2020-10-15 14:36:31
【问题描述】:

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

这是我的代码:

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()

【问题讨论】:

    标签: python python-3.x tkinter editor filedialog


    【解决方案1】:

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

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

    如您所见,您将文件的每一行插入到 0.0 索引 (0 row . 0 column) 这意味着它将在上一行的顶部添加下一行do 是在上一行之后添加一行。这可以通过将索引值更改为 "end" 而不是 0.0 来完成。

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

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

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

    【讨论】:

    • 读取整个文件并将其插入单个语句而不是逐行插入会更好。
    • @Saad,谢谢...我知道 0.0, "end", e.t.c 是如何工作的
    猜你喜欢
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2015-04-09
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    相关资源
    最近更新 更多