Python 使用Tkinter插入文本框

Python 使用Tkinter插入文本框,python,tkinter,Python,Tkinter,我正在尝试使用Tkinter将文本插入文本框。我试图插入从文件中检索到的信息,但我将其归结为一个更简单的问题,它显示出相同的问题: class Main(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.init_ui() def helloCallBack(self): self.t

我正在尝试使用Tkinter将文本插入文本框。我试图插入从文件中检索到的信息,但我将其归结为一个更简单的问题,它显示出相同的问题:

class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.init_ui()

    def helloCallBack(self):
        self.txt.insert("lol")

    def init_ui(self):    
        self.txt = Text(root, width=24, height = 10).grid(column=0, row = 0)

        load_button = Button(root, text="Load Wave Data", command = self.helloCallBack).grid(column=1, row = 0, sticky="E")

def main():
    ex = Main(root)
    root.geometry("300x250+300+300")
    root.mainloop()
我想让它做的是,每当我按下按钮,它就会将
lol
插入文本框,但我得到了错误

AttributeError:“非类型”对象没有属性“插入”


如何解决此问题?

要插入文本,您需要指明要从何处开始插入文本:

self.txt.insert(0, "lol")
  • 您需要在单独的行中调用
    grid
    。因为该方法返回
    None
    ;使
    self.txt
    引用
    None
    而不是
    Text
    小部件对象

    def init_ui(self):
        self.txt = Text(root, width=24, height=10)
        self.txt.grid(column=0, row=0)
    
        load_button = Button(root, text="Load Wave Data", command=self.helloCallBack)
        load_button.grid(column=1, row=0, sticky="E")
    
  • 您需要指定插入文本的位置

    def helloCallBack(self):
        self.txt.insert(END, "lol")