下面是一個使用tkinter和圖靈機(jī)器人API制作的簡單智能聊天系統(tǒng)的Python小項目。首先,確保你已經(jīng)安裝了tkinter
和requests
模塊。
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_KEY
和YOUR_USER_ID
為你在圖靈機(jī)器人平臺上獲得的API密鑰和用戶ID。
運(yùn)行代碼后,將會彈出一個窗口,你可以在聊天框中輸入與機(jī)器人進(jìn)行對話。機(jī)器人將會通過圖靈機(jī)器人API返回回復(fù),并在聊天框中顯示。