Hassan
Hassan

Reputation: 53

How to save text from entry? (Python)

I'm new to python and coding in general. I'm wondering how you can save the text from answering questions to a text file. It's a diary so every time I write things down and click add, I want it to add to a text file.

cue = Label(text="What happened?")
cue.pack()

e_react = StringVar()
e = Entry(root, textvariable=e_react, width=40, bg="azure")
e.pack()

def myclick():
    cue = "Cue: " + e.get()
    myLabel = Label(root, text=cue, bg="azure")
    myLabel.pack()

myButton = Button(root, text="Add", command=myclick)
myButton.pack()

react = Label(text="How did you react?")
react.pack()

e1 = Entry(root, width=40, bg="azure")
e1.pack()


def myclick():
    react = "Reacted by: " + e1.get()
    myLabel = Label(root, text=react, bg="azure")
    myLabel.pack()

myButton = Button(root, text="Add", command=myclick)
myButton.pack()

f = open("Hey.txt", "a")
f.write(e_react.get())
f.close()

I tried saving it as a String Variable, but it says I can't do that for appending files.

Many thanks!

Upvotes: 5

Views: 131

Answers (1)

ron_olo
ron_olo

Reputation: 146

Is this what you need?

from tkinter import *


root = Tk()
root.title("MyApp")

cue = Label(text="What happened?")
cue.pack()

e_react = StringVar()
e = Entry(root, textvariable=e_react, width=40, bg="azure")
e.pack()

def myclick():
    cue = "Cue: " + e.get()
    myLabel = Label(root, text=cue, bg="azure")
    myLabel.pack()
    f = open("Hey.txt", "a")
    f.write(e.get() + "\n")
    f.close()


myButton = Button(root, text="Add", command=myclick)
myButton.pack()

react = Label(text="How did you react?")
react.pack()

e1 = Entry(root, width=40, bg="azure")
e1.pack()


def myclick():
    react = "Reacted by: " + e1.get()
    myLabel = Label(root, text=react, bg="azure")
    myLabel.pack()
    f = open("Hey.txt", "a")
    f.write(e1.get() + "\n")
    f.close()

myButton = Button(root, text="Add", command=myclick)
myButton.pack()



root.mainloop()

Upvotes: 2

Related Questions