简体   繁体   中英

Revered Order When Open a File in the Editor

So I'm making a simple text editor with Python Tkinter . On the top side there's 2 buttons: "save" and "open".(they show open/save as dialogue windows). It's alright with the save button, but when i want to open a file in my editor it displays with reversed order .

There's my code:

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

Your problem is very simple to solve and the problem is with the following part of the code

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

As you can see you are inserting each line of the file to 0.0 index (0 row. 0 column) which means it is adding the next line on top of the previous line all you have to do is add the line after the previous line. That can be done by changing the index value to "end" instead of 0.0 .

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

Like being mentioned in the below comment , If you just want to insert the whole file into the Text widget at once then you can just do the following.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM