繁体   English   中英

在Tkinter.Text区域中显示用户输入

[英]Display user input in Tkinter.Text area

我试图从输入框中获取用户输入,一旦按下按钮,则将其显示在tk.Text()中。 我没有在标签中这样做的原因是因为我希望gui看起来像这样:

用户:嘿

回应:怎么了

用户:没事

我看了一下这个文档: http : //effbot.org/tkinterbook/text.htm并且示例在这里使用但是无法正常工作。

result = None
window = Tk()

def Response():
    global result
    result = myText.get()

#The below print displays result in console, I'd like that in GUI instead.
    #print "User: ", result

#Creating the GUI
myText = tk.StringVar()
window.resizable(False, False)
window.title("Chatbot")
window.geometry('400x400')
User_Input = tk.Entry(window, textvariable=myText, width=50).place(x=20, y=350)
subButton = tk.Button(window, text="Send", command=Response).place(x =350, y=350)
displayText = Text(window, height=20, width=40)
displayText.pack()
displayText.configure(state='disabled')
scroll = Scrollbar(window, command=displayText).pack(side=RIGHT)
window.mainloop()

我尝试过 displayText.insert(window,result)displayText.insert(End, result)

但是当我提交文本时仍然一无所获。 关键是显然保留用户的最后存储的文本,而不是覆盖它,而只是在彼此之间显示每个输入,而不是覆盖它,我建议文本是实现此目的的最佳方法。

UPDATE

感谢Kevin的评论和回答,用户文本现在显示在gui中,但是当我输入内容并再次单击send时,它会显示在侧面,如下所示:

HeyHey

而不是 :

我的聊天机器人已链接到Dialogflow,因此在每个用户输入之间,聊天机器人都会响应。

正如jasonharper在注释中指出的那样,您需要先取消禁用文本框,然后才能向其中添加文本。 此外, displayText.insert(window,result)不是正确的调用方式。 insert的第一个参数应该是索引,而不是window对象。

尝试:

def Response():
    #no need to use global here
    result = myText.get()
    displayText.configure(state='normal')
    displayText.insert(END, result)
    displayText.configure(state='disabled')

(取决于最初导入tkinter.END方式,您可能需要执行tk.ENDtkinter.END而不是END 。这很难分辨,因为您没有提供代码的那一部分)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM