Search code examples
pythonpython-3.xtkintersavetkinter-entry

How can I add 'Save', 'Copy', and 'Paste' in Tkinter Notepad?


I am learning (Tkinter)Python. I want to add 'Save', 'Copy', and 'Paste' functionalities in my tkinter app called 'Notepad' Here is my code:

from tkinter import *
import os


window=Tk()

window.title("Simple Notepad")

def save():
    if t1_value.get() == "":
        t1.insert(END, "Please add text to save it")
    else:
        t1_value.get().save("New-file-1.txt")


t1_value=StringVar()
t1=Text(window)
t1.grid(row=0,column=0,columnspan=6,padx=7,pady=7)

b1=Button(window,text="Close",width=15,command=window.destroy)
b1.grid(row=1,column=0,padx=7,pady=7)

b2=Button(window,text="Copy",width=15)
b2.grid(row=1,column=1,padx=7,pady=7)

b3=Button(window,text="Paste",width=15)
b3.grid(row=1,column=2,padx=7,pady=7)

b4=Button(window,text="Save",width=15,command=save)
b4.grid(row=1,column=3,padx=7,pady=7)

window.mainloop()

"Save" function from above isn't working !

Please tell me the method to add these above functionalities to this simple Tkinter notepad!


Solution

  • You want to make Notepad what can load and save. right? I think use the write , read and with function is more better for you. First, you have to check the filename and then definition the save and open function

    filename='mynote.txt'
    
    def open_file():
        if os.path.isfile(filename) :
            with open('mynote.txt', 'r', encoding='utf8') as mynote_read:
                t1.delete('1.0',END) 
                t1.insert(END, mynote_read.read())
                t1.see(END)
    def save_file():
        with open('mynote.txt','w',encoding='utf8') as mynote_write:
            mynote_write.write(t1.get('1.0',END))
    
            t1.delete('1.0',END)
            mynote_write.close()