温馨提示×

Python小项目:利用tkinter与图灵机器人制作智能聊天系统

小云
101
2023-10-11 11:25:14
栏目: 编程语言

下面是一个使用tkinter和图灵机器人API制作的简单智能聊天系统的Python小项目。首先,确保你已经安装了tkinterrequests模块。

import tkinter as tk
import requests
def get_response(message):
url = 'http://openapi.tuling123.com/openapi/api/v2'
data = {
"reqType":0,
"perception": {
"inputText": {
"text": message
}
},
"userInfo": {
"apiKey": "YOUR_API_KEY",
"userId": "YOUR_USER_ID"
}
}
response = requests.post(url, json=data).json()
result = response['results'][0]['values']['text']
return result
def send_message(event=None):
message = entry.get()
if message.strip() != '':
chat_log.config(state=tk.NORMAL)
chat_log.insert(tk.END, "You: " + message + '\n')
chat_log.config(state=tk.DISABLED)
chat_log.yview(tk.END)
response = get_response(message)
chat_log.config(state=tk.NORMAL)
chat_log.insert(tk.END, "Bot: " + response + '\n')
chat_log.config(state=tk.DISABLED)
chat_log.yview(tk.END)
entry.delete(0, tk.END)
root = tk.Tk()
root.title("Chatbot")
frame = tk.Frame(root)
scrollbar = tk.Scrollbar(frame)
chat_log = tk.Text(frame, width=80, height=20, state=tk.DISABLED, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
chat_log.pack(side=tk.LEFT, fill=tk.BOTH, pady=10)
frame.pack()
entry = tk.Entry(root, width=80)
entry.bind("<Return>", send_message)
entry.pack(pady=10)
send_button = tk.Button(root, text="Send", command=send_message)
send_button.pack()
root.mainloop()

注意替换YOUR_API_KEYYOUR_USER_ID为你在图灵机器人平台上获得的API密钥和用户ID。

运行代码后,将会弹出一个窗口,你可以在聊天框中输入与机器人进行对话。机器人将会通过图灵机器人API返回回复,并在聊天框中显示。

0