【问题标题】:How to save text from entry? (Python)如何保存条目中的文本? (Python)
【发布时间】:2020-10-04 09:09:19
【问题描述】:

我是 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()

我尝试将其保存为字符串变量,但它说我无法为附加文件执行此操作。

非常感谢!

【问题讨论】:

  • 关键是使用 StringVar.get() 方法,正如接受的答案中使用的那样。
  • @TerryJanReedy:stringvar 在这里是完全可选的。在小部件本身上调用 get() 也可以。

标签: python python-3.x tkinter


【解决方案1】:

这是你需要的吗?

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()

【讨论】:

  • 如果您添加了对您所做的不同之处的描述,这个答案会更好。否则我们必须将这段代码与原始代码逐行​​逐字符进行比较。
猜你喜欢
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2017-09-22
  • 2022-08-23
  • 1970-01-01
  • 2014-11-01
相关资源
最近更新 更多