'NoneType'对象没有属性'insert'

时间:2017-12-14 17:13:49

标签: python-3.x tkinter

我正在尝试在Python中创建一个用于搜索目录并带回匹配的GUI。但是,每当我运行它时,我得到错误'NoneType'对象没有文本字段插入部分的属性'insert'。我做错了什么?

from tkinter import *
root = Tk()
root.title("ICD-10-CM Lookup")
ICD_10_CM = StringVar()
label1 = Label(root, text="ICD-10_CM Code").grid(row=0, column=0)
query = Entry(root, textvariable=ICD_10_CM).grid(row=0, column=1)

def search():
    infile = open("icd10cm.txt", "r")
    for line in infile:
       line = line.strip()
       elements = line.split("\t")
       if str(query) in elements[0]:
           textfield.insert(elements[1])
       elif str(query) in elements[1]:
           textfield.insert(elements[0])
    infile.close()

search_button = Button(root, text="Search",   command=search).grid(row=2,column=0)
textfield = Text(root).grid(row=1,column=1,rowspan=2)
root.mainloop()

1 个答案:

答案 0 :(得分:0)

您的textfield变量为None,因为grid方法返回None,因此您需要将初始化和网格方法分开。查询也一样。此外,insert方法需要两个args:index和chars。

from tkinter import *
root = Tk()
root.title("ICD-10-CM Lookup")
ICD_10_CM = StringVar()
label1 = Label(root, text="ICD-10_CM Code").grid(row=0, column=0)
query = Entry(root, textvariable=ICD_10_CM)
query.grid(row=0, column=1)


def search():
    infile = open("icd10cm.txt", "r")
    for line in infile:
        line = line.strip()
        elements = line.split("\t")
        if str(query.get()) in elements[0]:
            textfield.insert(INSERT, elements[1])
        elif str(query.get()) in elements[1]:
            textfield.insert(INSERT, elements[0])
        textfield.insert(END, '\n')
    infile.close()


search_button = Button(root, text="Search", command=search).grid(row=2, column=0)
textfield = Text(root)
textfield.grid(row=1, column=1, rowspan=2)
root.mainloop()