【问题标题】:Display user input in Tkinter.Text area在 Tkinter.Text 区域显示用户输入
【发布时间】:2018-08-02 12:24:09
【问题描述】:

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

用户:嘿

回应:怎么了

用户:什么都没有……

我看过这个文档:http://effbot.org/tkinterbook/text.htm 示例使用here,但无法让我的工作。

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)

但是当我提交文本时仍然一无所获。关键是显然保留用户最后存储的文本,而不是覆盖它,简单地将每个输入显示在彼此下方,我被告知 Text 是最好的方法。

更新

感谢 cmets 和 Kevin 的回答,用户文本现在显示在 gui 中,但是当我输入内容并再次单击发送时,它会转到一边,如下所示:

嘿嘿

而不是:

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

【问题讨论】:

  • 使用state='disabled',Text 确实被禁用了——禁止编程更改以及手动输入。您必须在插入文本之前暂时启用它,然后再次禁用它。
  • 感谢您的回复,这样的事情仍然不起作用,我是否认为我需要它把它放在def Response()displayText.configure(state='normal') displayText.insert(window,result ) displayText.configure(state='disabled')
  • @jasonharper 现已排序,已投票,感谢您的帮助。

标签: python tkinter


【解决方案1】:

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

试试:

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

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

【讨论】:

  • 感谢@Kevin 的回复,这似乎已经解决了问题并用输出更新了问题,我的印象是 END 指示了一个可能的新行?
  • 我不这么认为。如果需要换行,可以自己添加:displayText.insert(END, "\n" + result)
  • 忽略这个,认为我用 + '\n' 解决了附加定位谢谢
猜你喜欢
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 2019-03-03
相关资源
最近更新 更多