【发布时间】:2022-09-30 23:15:46
【问题描述】:
您好我正在尝试编写一个聊天机器人,它接受以下输入:姓名和姓氏 这个想法是,当用户单击“发送”按钮时,输入存储在“名称”变量中。文本框被清除,当用户再次单击按钮时,新输入应进入另一个变量“姓氏”。 我怎样才能做到这一点?我想在聊天机器人的 GUI 中打印“Hello name + lastname”
这是我到目前为止所拥有的:
from tkinter import * #GUI library a
import sys
root = Tk() #create a tkinter object which represents the parent window
root.title(\"Chat Bot\")
root.geometry(\"400x500\")
root.resizable(width=FALSE, height=FALSE)
chatWindow = Text(root, bd=1, bg=\"black\", width=\"50\", height=\"8\", font=(\"Arial\", 12), foreground=\"#00ffff\") #create a window for the conversation and place it on the parent window
chatWindow.place(x=6,y=6, height=385, width=370)
messageWindow = Text(root, bd=0, bg=\"black\",width=\"30\", height=\"4\", font=(\"Arial\", 23), foreground=\"#00ffff\") #create the text area where the message will be entered and place it on the parent window
messageWindow.place(x=128, y=400, height=88, width=260)
def get():
name = messageWindow.get(\'1.0\', END) #\"1.0\" means that the input should be read from line one, character zero (ie: the very first character). END is an imported constant which is set to the string \"end\". The END part means to read until the end of the text box is reached.
messageWindow.delete(\'1.0\', END)
Button= Button(root, text=\"Send\", command = get, width=\"12\", height=5,
bd=0, bg=\"#0080ff\", activebackground=\"#00bfff\",foreground=\'#ffffff\',font=(\"Arial\", 12))
Button.place(x=6, y=400, height=88) #create button to send the message and place it in the parent window
#Whenever I am calling print) I am actually calling sys.stdout.write() so with this function redirector which redirect the print() to the GUI
def redirector(inputStr):
chatWindow.insert(INSERT, inputStr)
sys.stdout.write = redirector #whenever sys.stdout.write is called, redirector is called.
print(\"Hello, I am your awesome assistant today. \\n\")
print(\"Please enter your name and last name. \\n\")
root.mainloop()
标签: python tkinter data-science