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!

2
  • The key is to use the StringVar.get() method, as used in the accepted answer. Commented Oct 4, 2020 at 20:25
  • @TerryJanReedy: the stringvar is completely optional here. Calling get() on the widget itself will work just as well. Commented Oct 10, 2020 at 21:19

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.