2014-12-03 121 views
-2

我正在嘗試編寫一個程序,該程序是一本讓您可以添加食譜等的食譜書,但我對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) 
+0

我不知道這是不是你的具體問題的原因,但你不能創建一個Tkinter的部件,併網它,並將結果全部分配在一行上。所有的itemtext,input_item,quantitytext,input_quantity,unittext,input_unit變量都是None。在一條線上創建和分配,然後在第二條線上分配網格。 – Kevin 2014-12-03 20:48:43

+0

另外,您正在以寫入模式打開文件。這會截斷它(刪除它最初包含的內容)。你確定你不想追加模式('open(「StoredRecipes.txt」,「a」)')? – iCodez 2014-12-03 21:06:10

回答

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)