5

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!

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Hassan
  • 53
  • 3

1 Answers1

2

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()
ron_olo
  • 146
  • 6
  • This answer would be better if you added a description of what you did differently. Otherwise we have to compare this code to the original line-by-line and character-by-character. – Bryan Oakley Oct 10 '20 at 21:20