我不知道我在做什么错!
我试图将tkinter条目中的数据写入/追加到txt
文件中。条目进入一个列表,我将其追加到文本文件中。但这并不需要我的新条目,只需我已经定义的文本。
这是我的代码:
from tkinter import *
root = Tk()
# Input
# -----------------------------------------------------
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
ivnget = ivn.get()
inputVarName.grid(row=0, column=0)
# Input
# -----------------------------------------------------
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
ivnget2 = ivn2.get()
inputVarName2.grid(row=1, column=0)
# Collecting data (entry)
# --------------------------------------------------------------------------------------
content_list = [ivnget, ivnget2]
# --------------------------------------------------------------------------------------
print("\n".join(content_list))
def writetofile():
with open("dataoutput2.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
# Button that applies entries to file
# --------------------------------------------------------------------------------------
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
# --------------------------------------------------------------------------------------
root.mainloop()
答案 0 :(得分:2)
您已将get
命令放在功能writetofile
之外。
试试:
from tkinter import *
root = Tk()
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
print("\n".join(content_list))
with open("dataoutput2.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
root.mainloop()