使用 Tkinter 插入文本框

Nan*_*nor 3 python tkinter

我正在尝试使用 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()
Run Code Online (Sandbox Code Playgroud)

我想要它做的是每当我按下按钮时它就会插入lol文本框,但我收到错误

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

我该如何解决?

fal*_*tru 6

  1. 您需要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")
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您需要指定插入文本的位置。

    def helloCallBack(self):
        self.txt.insert(END, "lol")
    
    Run Code Online (Sandbox Code Playgroud)