首页 > 解决方案 > 为什么在检查现有数据时出现错误(python)

问题描述

代码存在问题,它显示有关缩进块的错误。可以从不同的角度检查此代码吗?并解释为什么 if 语句有问题?也许您对当前代码也有一些建议。

亲切的问候,J。

from tkinter import *

root = Tk()
root.geometry("700x700")
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 printSomething():
    with open('help.txt') as f:
        r = f.read()
    label = Label(root, text=r)
    label.grid()


def checkdata():
    with open('help.txt') as f:
        r = f.read()
    return r.split("\n")


def writetofile():
    exist_data = checkdata()
    content_list = [ivn.get(), ivn2.get()]
    with open("help.txt", "a") as f:
        for item in content_list:
        if item in exist_data:
            msg = "Already exist "+item
            label = Label(root, text=msg)
            label.grid()
        elif not item in exist_data:
            f.write("%s\n" % item)


applyButton = Button(root, text="Add Data", command=writetofile)
applyButton.grid(row=2, column=1)

veiwButton = Button(root, text='View Data', command=printSomething)
veiwButton.grid(row=3, column=1)

root.mainloop()

标签: pythonexceltkinter

解决方案


将您的功能更改writetofile()为:

def writetofile():
    exist_data = checkdata()
    content_list = [ivn.get(), ivn2.get()]
    with open("help.txt", "a") as f:
        for item in content_list:
            if item in exist_data:
                msg = "Already exist "+item
                label = Label(root, text=msg)
                label.grid()
            elif not item in exist_data:
                f.write("%s\n" % item)

我只是在后面的行缩进for item in exist_data:


推荐阅读