Tkinter无法写入文本文件
问题描述:
我正在尝试编写一个程序,该程序是一本让您可以添加食谱等的食谱书,但我对Python和Tkinter颇为新颖。Tkinter无法写入文本文件
#New Recipe Screen
def click(key):
new_recipe = Tk()
new_recipe.title("New Recipe")
itemtext = Label(new_recipe, text="Item").grid(row=0, column=0)
input_item = Entry(new_recipe).grid(row=0, column=1)
quantitytext = Label(new_recipe, text="Quantity").grid(row=1, column=0)
input_quantity =Entry(new_recipe).grid(row=1, column=1)
unittext = Label(new_recipe, text="Unit").grid(row=2, column=0)
input_unit = Entry(new_recipe).grid(row=2, column=1)
fin_btn_text = "Finish"
def write(x=fin_btn_text):
click(x)
dataFile = open("StoredRecipes.txt", "w")
dataFile.write(str(input_item,) + "\n")
new_recipe.destroy
finish_btn = Button(new_recipe, text=fin_btn_text, command=write).grid(row=3, column=0)
答
两个问题在这里:
-
您不关闭文件时,你用它做。有些系统要求您执行此操作才能执行更改。无论是拨打
dataFile.close()
你write
函数结束或者使用with-statement打开文件(它会自动关闭它,当你完成):def write(x=fin_btn_text): click(x) with open("StoredRecipes.txt", "w") as dataFile: dataFile.write(str(input_item,) + "\n") new_recipe.destroy() # Remember to call this
-
由于@Kevin在a comment指出,你不能叫
.grid
与创建小部件相同。.grid
方法在原地工作并始终返回None
。因此,应在自己的行建立小工具后叫:itemtext = Label(new_recipe, text="Item") itemtext.grid(row=0, column=0)
我不知道这是不是你的具体问题的原因,但你不能创建一个Tkinter的部件,并网它,并将结果全部分配在一行上。所有的itemtext,input_item,quantitytext,input_quantity,unittext,input_unit变量都是None。在一条线上创建和分配,然后在第二条线上分配网格。 – Kevin 2014-12-03 20:48:43
另外,您正在以写入模式打开文件。这会截断它(删除它最初包含的内容)。你确定你不想追加模式('open(“StoredRecipes.txt”,“a”)')? – iCodez 2014-12-03 21:06:10