Tkinter无法写入文本文件

时间:2014-12-03 20:46:31

标签: python file tkinter

我正在尝试编写一个程序,这是一本食谱书,可以让你添加食谱等。虽然我对Python和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)

1 个答案:

答案 0 :(得分:0)

这里有两个问题:

  1. 完成后,您没有关闭文件。某些系统要求您执行此操作以提交更改。在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
    
  2. 正如@Kevin在a comment中指出的那样,您无法在创建窗口小部件的同一行调用.grid.grid方法就地工作,并始终返回None。因此,在创建窗口小部件后应该在它自己的行上调用它:

    itemtext = Label(new_recipe, text="Item")
    itemtext.grid(row=0, column=0)