我是 Python 和一般编码的新手。我想知道如何将回答问题的文本保存到文本文件中。这是一本日记,所以每次我写下内容并单击添加时,我都希望将其添加到文本文件中。
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()
我尝试将它保存为字符串变量,但它说我不能为附加文件这样做。非常感谢!
最佳答案
这是你需要的吗?
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()
关于python - 如何保存输入的文本? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64192852/