Tkinter文本插入:"'Nonetype'对象没有属性'insert'

Qua*_*ter 2 python user-interface tkinter insert nonetype

一般来说编码比较新,并且一直在尝试为Python创建一个简单的聊天客户端.尝试使用GUI,并遇到下面显示的问题.

我有一个正常运行的GUI,并使用"example.get()"函数从输入框中检索字符串文本.程序然后将文本打印到命令提示符(只是为了证明它已被检索)然后应该将它放在一个文本框中,但是它给了我一个"Nonetype"错误.代码如下.有谁知道如何解决这个问题?

谢谢

from tkinter import *

#Create GUI
root=Tk()
root.title("Chat test")
root.geometry("450x450+300+300")

#Declare variables
msg=StringVar()

#Get and post text to chat log
def postaction():
    msg1=msg.get()
    print(msg1)
    chatlog.insert(INSERT,msg1+'\n')
    root.mainloop()

#Build GUI components
chatlog=Text(root, height=10, state=DISABLED).pack(side=TOP, fill=X)
entry=Entry(root, textvariable=msg).pack(side=BOTTOM, fill=X)
button=Button(root, command=postaction, text="Button").pack()
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 8

.pack小部件的方法总是返回None.因此,您需要将呼叫.pack置于他们自己的线路上:

chatlog=Text(root, height=10, state=DISABLED)
chatlog.pack(side=TOP, fill=X)
entry=Entry(root, textvariable=msg)
entry.pack(side=BOTTOM, fill=X)
button=Button(root, command=postaction, text="Button")
button.pack()
Run Code Online (Sandbox Code Playgroud)