python - 为什么在检查现有数据时出现错误(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()
解决方案
将您的功能更改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:
推荐阅读
- c# - 对象的属性是否在 C# 中与对象一起被垃圾收集,或者它们具有单独的 gc 机制
- python - 如何使用日志值向 Pandas 数据框添加新列
- .net-core - dotnet 控制台应用程序,使用通用主机,HostedService,Windows 任务计划程序保持运行状态
- java - 类图的实现
- sql-server - 使用 SQL 后端的 Access 查询中出现无法解释的“无效操作”错误
- linux - 我不明白这段代码的含义,你能帮帮我吗?
- javascript - 在echarts中,如何让两条x轴固定显示在一条线的左右两边
- python-3.x - 使用 KMeans 进行 Floyd 抖动
- reactjs - 为什么 401 错误没有被 reactJS 中的 fetch 函数捕获?
- java - 为什么 ForkJoinPool::shutdownNow 返回一个空列表?