Tkinter无法写入文本fi

2024-04-27 19:37:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个程序,这是一个食谱书,让你添加食谱等,我是相当新的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)

Tags: textnewinputrecipecolumnlabelgridwrite
1条回答
网友
1楼 · 发布于 2024-04-27 19:37:24

这里有两个问题:

  1. 处理完文件后不能关闭它。有些系统要求您这样做以提交更改。在write函数末尾调用dataFile.close(),或者使用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)
    

相关问题 更多 >