用python写一个对话窗口程序例子
时间: 2023-04-05 17:01:22 浏览: 91
很高兴回答您的问题。以下是一个简单的 Python 对话窗口程序的示例代码:
```python
from tkinter import *
def send_message():
message = entry.get()
if message.strip() != "":
chat_log.config(state=NORMAL)
chat_log.insert(END, "You: " + message + "\n")
chat_log.config(foreground="#442265", font=("Verdana", 12 ))
entry.delete(0, END)
def bot_response():
message = "Hello! How can I assist you today?"
chat_log.config(state=NORMAL)
chat_log.insert(END, "Bot: " + message + "\n")
chat_log.config(foreground="#442265", font=("Verdana", 12 ))
root = Tk()
root.title("Chatbot")
chat_log = Text(root, bd=0, bg="white", height="8", width="50", font="Arial")
chat_log.config(state=DISABLED)
scrollbar = Scrollbar(root, command=chat_log.yview)
chat_log['yscrollcommand'] = scrollbar.set
entry = Entry(root, bd=0, bg="white", width="30", font="Arial")
entry.bind("<Return>", send_message)
send_button = Button(root, text="Send", width="12", height=5,
bd=0, bg="#32de97", activebackground="#3c9d9b",
foreground='#ffffff', font=("Arial", 12), command=send_message)
# Place all components on the screen
scrollbar.place(x=476,y=6, height=386)
chat_log.place(x=6,y=6, height=386, width=470)
entry.place(x=128, y=401, height=40, width=370)
send_button.place(x=6, y=401, height=40)
bot_response()
root.mainloop()
```
这个程序使用了 Python 的 tkinter 库来创建一个简单的对话窗口。用户可以输入文本消息并点击“发送”按钮,程序会将消息显示在聊天记录中,并自动回复一个预设的消息。您可以根据需要修改代码来实现更复杂的对话逻辑。