Save text file in Python

Asked

Viewed 3,520 times

1

I am creating a simple text editor with Python and Tkinter and I want to do a function to save what was typed. I made the save function, but it only creates the txt file and does not save what was typed in Text. How can I do this?

Here is my code:

from tkinter import *
from tkinter import filedialog


def Save():
    name = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
    print(name)


root = Tk()

menu = Menu(root)
root.config(menu=menu)

subMenu = Menu(menu, tearoff=0)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Save", command=Save)

textField = Text(root)
textField.pack(side=LEFT, expand=True, fill='both')

scrollBar = Scrollbar(root)
scrollBar.pack(side=RIGHT, fill=Y)

scrollBar.config(command=textField.yview)
textField.config(yscrollcommand=scrollBar.set)

root.mainloop()

1 answer

1


I ended up finding a solution on the Internet. It turns out that on the Python site where it shows how to save and open a file, it does not explain the part of Oce having to take the text of "Text" and then write it in the file created.

The function to save the typed text looks like this:

def Save():
    name = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
    t = textField.get(0.0, END)  # Pega o texto do textField
    name.write(t.rstrip())  # Escreve o texto no arquivo criado

Browser other questions tagged

You are not signed in. Login or sign up in order to post.