NoneType错误 self.widget.insert

-1 投票
1 回答
611 浏览
提问于 2025-04-18 06:23

我在我的应用程序中想要有一个输出框。当我运行它的时候,出现了一个错误:NoneType object has no attribute insert,这个错误出现在self.widget.insert('end', string)这行代码上。希望能得到一些帮助。

import Tkinter as tk
import sys

class Test(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        toolbar = tk.Frame(self).grid()
        tk.Button(self, text="print to stdout", command=self.print_stdout).grid()

        self.text= tk.Text(self).grid()
        sys.stdout= Output(self.text)


    def print_stdout(self):
        print "Hello"
        print "This is test"

class Output(object):
    def __init__(self, widget):
        self.widget = widget

    def write(self,string):
        self.widget.insert('end', string)

app = Test()
app.mainloop()

1 个回答

1

你的问题出现在这一行:

self.text= tk.Text(self).grid()

grid 并没有明确地 return 任何东西,所以这实际上就是把 self.text = None 设置为 None。这个值接着被传递给 Output.__init__,最后在 write 中被访问。

不如把它分成两个步骤来做:

 self.text = tk.Text(self)
 self.text.grid()

撰写回答