L
L
leon -----2021-11-25 23:05:43
Python
leon -----, 2021-11-25 23:05:43

Notepad (which I wrote myself) does not work correctly. What to change in the program?

I wrote a notebook for my portfolio. But it doesn't work correctly for me. I open a file. I save. and when reopening, the text is duplicated.
Here is an example:
1 Open a file.
619feae891795600692129.png
2 Editing the file.
619feb1c0d0e0756301237.png
3 Save and open.
619feb9f0fcdd601641935.png
Here is the code itself:

from tkinter import *
from tkinter import Menu
from tkinter import scrolledtext
from tkinter.filedialog import *
from tkinter import messagebox

def new_file():
    sa = asksaveasfilename()
    content = txt.get(1.0,END)
    f = open(sa + ".txt", "w", encoding='utf-8')
    f.write(content)
    txt.delete(1.0, END)
    f = open(sa, 'r')
    txt.insert(INSERT, str(f.read()))
    root.title(str(sa))

def save_file_kak():
    sa = asksaveasfilename()
    content = txt.get(1.0,END)
    f = open(sa + ".txt", "w", encoding='utf-8')
    f.write(content)
  
def open_file():
        res = messagebox.askokcancel('Открыть файл', 'Все не сохраненные данные не сохранятся!                              Открыть новый файл?')
        if res == True:
            global f
            global openfile
            openfile = askopenfilename(parent=root)
            txt.delete(1.0, END)
            f = open(openfile, 'r+', encoding='utf-8')
            s = f.read()
            txt.insert(1.0, s)
            root.title(str(openfile))

def save_file():
    f.write(txt.get("1.0", 'end'))



titl = 'Новый текстовый документ.txt'
root = Tk()
root.title(titl)
root.geometry('700x500')


txt = scrolledtext.ScrolledText(root,width=800,height=800)
txt.pack()

menu = Menu(root)
filemenu = Menu(menu, tearoff=0)
filemenu.add_command(label='Новый Файл')
filemenu.add_command(label='Открыть файл', command=open_file)
filemenu.add_command(label='Сохранить', command=save_file)
filemenu.add_command(label='Сохранить как', command=save_file_kak)
menu.add_cascade(label='Файл',menu=filemenu)

root.config(menu=menu)
root.mainloop()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2021-11-26
@Stalker_RED

Take a closer look at the mode in which the file is opened. w, r+, that's it.

R
Ricardo Sanchez, 2021-11-26
@yakovlev_13

Notepad knows that you are Leonid and disagrees with Konstantin)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question