Nanor
Nanor

Reputation: 2540

Inserting to a textbox with Tkinter

I'm trying to insert text into a textbox using Tkinter. I'm trying to insert information retrieved from a file but I've boiled it down to something simpler which exhibits the same problem:

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()

What I want it to do is whenever I press the button it inserts lol into the text box but I get the error

AttributeError: 'NoneType' object has no attribute 'insert'

How do I fix this?

Upvotes: 3

Views: 17841

Answers (2)

falsetru
falsetru

Reputation: 368894

  1. You need to call grid in separated line. Because the method return None; causing the self.txt to reference None instead of Text widget object.

    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")
    
  2. You need to specify where to insert the text.

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

Upvotes: 6

Dair
Dair

Reputation: 16240

To insert you need to indicate where you want to start inserting text:

self.txt.insert(0, "lol")

Upvotes: 3

Related Questions