Save text file in Python

3

I'm creating a simple text editor with Python and Tkinter and I want to do a function to save what was typed. I did 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()
    
asked by anonymous 04.02.2018 / 17:52

1 answer

2

I just found a solution on the internet. It turns out that in the Python site where it shows how to save and open a file, it does not explain how you have to get the text from "Text" and then write it in the created file.

The function to save 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
    
04.02.2018 / 18:57